#3508
Implement Router
MediumArrayHash TableBinary SearchDesignQueueOrdered SetHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(1)Space O(n)
Use a deque for efficient packet management and a hash set for quick duplicate checks. This allows for O(1) operations for adding and removing packets.
⚙️
Algorithm
3 steps- 1Step 1: Use a deque to store packets in order of arrival.
- 2Step 2: Use a hash set to track unique packets for quick duplicate checks.
- 3Step 3: When adding a packet, check the hash set; if it's unique, add it to the deque and hash set, and remove the oldest if necessary.
solution.py17 lines
1from collections import deque
2class Router:
3 def __init__(self, memoryLimit):
4 self.memoryLimit = memoryLimit
5 self.packets = deque()
6 self.packetSet = set()
7
8 def addPacket(self, source, destination, timestamp):
9 packet = (source, destination, timestamp)
10 if packet in self.packetSet:
11 return False
12 if len(self.packets) >= self.memoryLimit:
13 old_packet = self.packets.popleft()
14 self.packetSet.remove(old_packet)
15 self.packets.append(packet)
16 self.packetSet.add(packet)
17 return Trueℹ
Complexity note: Adding and removing packets from deque and checking duplicates in a set are O(1) operations.
- 1Use a deque for efficient FIFO management.
- 2Hash sets provide O(1) average time complexity for duplicate checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.