Approach
Breadth-first search
For Implement Router, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 48 lines of Python from the credited upstream file 3508.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue, cached states.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from dataclasses import dataclass2 3 4@dataclass(frozen=True)5class Packet:6 source: int7 destination: int8 timestamp: int9 10 11class Router:12 def __init__(self, memoryLimit: int):13 self.memoryLimit = memoryLimit14 self.uniquePackets: set[Packet] = set()15 self.packetQueue: collections.deque[Packet] = collections.deque()16 self.destinationTimestamps = collections.defaultdict(list)17 self.processedPacketIndex = collections.Counter()18 19 def addPacket(self, source: int, destination: int, timestamp: int) -> bool:20 packet = Packet(source, destination, timestamp)21 if packet in self.uniquePackets:22 return False23 if len(self.packetQueue) == self.memoryLimit:24 self.forwardPacket()25 self.packetQueue.append(packet)26 self.uniquePackets.add(packet)27 if destination not in self.destinationTimestamps:28 self.destinationTimestamps[destination] = []29 self.destinationTimestamps[destination].append(timestamp)30 return True31 32 def forwardPacket(self) -> list[int]:33 if not self.packetQueue:34 return []35 nextPacket = self.packetQueue.popleft()36 self.uniquePackets.remove(nextPacket)37 self.processedPacketIndex[nextPacket.destination] += 138 return [nextPacket.source, nextPacket.destination, nextPacket.timestamp]39 40 def getCount(self, destination: int, startTime: int, endTime: int) -> int:41 if destination not in self.destinationTimestamps:42 return 043 timestamps = self.destinationTimestamps[destination]44 startIndex = self.processedPacketIndex.get(destination, 0)45 lowerBound = bisect.bisect_left(timestamps, startTime, startIndex)46 upperBound = bisect.bisect_right(timestamps, endTime, startIndex)47 return upperBound - lowerBound48