Design a data structure that can efficiently manage data packets in a network router. Each data packet consists of the following attributes:
source: A unique identifier for the machine that generated the packet.
destination: A unique identifier for the target machine.
timestamp: The time at which the packet arrived at the router.
Implement the Router class:
Router(int memoryLimit): Initializes the Router object with a fixed memory limit.
memoryLimit is the maximum number of packets the router can store at any given time.
If adding a new packet would exceed this limit, the oldest packet must be removed to free up space.
bool addPacket(int source, int destination, int timestamp): Adds a packet with the given attributes to the router.
A packet is considered a duplicate if another packet with the same source, destination, and timestamp already exists in the router.
Return true if the packet is successfully added (i.e., it is not a duplicate); otherwise return false.
int[] forwardPacket(): Forwards the next packet in FIFO (First In First Out) order.
Remove the packet from storage.
Return the packet as an array [source, destination, timestamp].
If there are no packets to forward, return an empty array.
int getCount(int destination, int startTime, int endTime):
Returns the number of packets currently stored in the router (i.e., not yet forwarded) that have the specified destination and have timestamps in the inclusive range [startTime, endTime].
Note that queries for addPacket will be made in non-decreasing order of timestamp.
Router router = new Router(3); // Initialize Router with memoryLimit of 3.
router.addPacket(1, 4, 90); // Packet is added. Return True.
router.addPacket(2, 5, 90); // Packet is added. Return True.
router.addPacket(1, 4, 90); // This is a duplicate packet. Return False.
router.addPacket(3, 5, 95); // Packet is added. Return True
router.addPacket(4, 5, 105); // Packet is added, [1, 4, 90] is removed as number of packets exceeds memoryLimit. Return True.
router.forwardPacket(); // Return [2, 5, 90] and remove it from router.
router.addPacket(5, 2, 110); // Packet is added. Return True.
router.getCount(5, 100, 110); // The only packet with destination 5 and timestamp in the inclusive range [100, 110] is [4, 5, 105]. Return 1.
Router router = new Router(2); // Initialize Router with memoryLimit of 2.
router.addPacket(7, 4, 90); // Return True.
router.forwardPacket(); // Return [7, 4, 90].
router.forwardPacket(); // There are no packets left, return [].
Constraints:
2 <= memoryLimit <= 105
1 <= source, destination <= 2 * 105
1 <= timestamp <= 109
1 <= startTime <= endTime <= 109
At most 105 calls will be made to addPacket, forwardPacket, and getCount methods altogether.
queries for addPacket will be made in non-decreasing order of timestamp.
Solutions
Solution 1: Hash Map + Queue + Binary Search
We use a hash map \(\textit{vis}\) to store the hash values of packets that have already been added, a queue \(\textit{q}\) to store the packets currently in the router, a hash map \(\textit{idx}\) to record the number of packets already forwarded for each destination, and a hash map \(\textit{d}\) to store the list of timestamps for each destination.
For the \(\textit{addPacket}\) method, we compute the hash value of the packet. If it already exists in \(\textit{vis}\), we return \(\text{false}\); otherwise, we add it to \(\textit{vis}\), check if the current queue size exceeds the memory limit, and if so, call the \(\textit{forwardPacket}\) method to remove the oldest packet. Then, we add the new packet to the queue and append its timestamp to the corresponding destination's timestamp list, finally returning \(\text{true}\). The time complexity is \(O(1)\).
For the \(\textit{forwardPacket}\) method, if the queue is empty, we return an empty array; otherwise, we remove the packet at the head of the queue, delete its hash value from \(\textit{vis}\), update the number of forwarded packets for the corresponding destination, and return the packet. The time complexity is \(O(1)\).
For the \(\textit{getCount}\) method, we get the timestamp list and the number of forwarded packets for the given destination, then use binary search to find the number of timestamps within the specified range, and return that count. The time complexity is \(O(\log n)\), where \(n\) is the length of the timestamp list.
classRouter:def__init__(self,memoryLimit:int):self.lim=memoryLimitself.vis=set()self.q=deque()self.idx=defaultdict(int)self.d=defaultdict(list)defaddPacket(self,source:int,destination:int,timestamp:int)->bool:x=self.f(source,destination,timestamp)ifxinself.vis:returnFalseself.vis.add(x)iflen(self.q)>=self.lim:self.forwardPacket()self.q.append((source,destination,timestamp))self.d[destination].append(timestamp)returnTruedefforwardPacket(self)->List[int]:ifnotself.q:return[]s,d,t=self.q.popleft()self.vis.remove(self.f(s,d,t))self.idx[d]+=1return[s,d,t]deff(self,a:int,b:int,c:int)->int:returna<<46|b<<29|cdefgetCount(self,destination:int,startTime:int,endTime:int)->int:ls=self.d[destination]k=self.idx[destination]i=bisect_left(ls,startTime,k)j=bisect_left(ls,endTime+1,k)returnj-i# Your Router object will be instantiated and called as such:# obj = Router(memoryLimit)# param_1 = obj.addPacket(source,destination,timestamp)# param_2 = obj.forwardPacket()# param_3 = obj.getCount(destination,startTime,endTime)
classRouter{privateintlim;privateSet<Long>vis=newHashSet<>();privateDeque<int[]>q=newArrayDeque<>();privateMap<Integer,Integer>idx=newHashMap<>();privateMap<Integer,List<Integer>>d=newHashMap<>();publicRouter(intmemoryLimit){this.lim=memoryLimit;}publicbooleanaddPacket(intsource,intdestination,inttimestamp){longx=f(source,destination,timestamp);if(vis.contains(x)){returnfalse;}vis.add(x);if(q.size()>=lim){forwardPacket();}q.offer(newint[]{source,destination,timestamp});d.computeIfAbsent(destination,k->newArrayList<>()).add(timestamp);returntrue;}publicint[]forwardPacket(){if(q.isEmpty()){returnnewint[]{};}int[]packet=q.poll();ints=packet[0],d_=packet[1],t=packet[2];vis.remove(f(s,d_,t));idx.merge(d_,1,Integer::sum);returnnewint[]{s,d_,t};}privatelongf(inta,intb,intc){return((long)a<<46)|((long)b<<29)|(long)c;}publicintgetCount(intdestination,intstartTime,intendTime){List<Integer>ls=d.getOrDefault(destination,List.of());intk=idx.getOrDefault(destination,0);inti=lowerBound(ls,startTime,k);intj=lowerBound(ls,endTime+1,k);returnj-i;}privateintlowerBound(List<Integer>list,inttarget,intfromIndex){intl=fromIndex,r=list.size();while(l<r){intm=(l+r)>>>1;if(list.get(m)<target){l=m+1;}else{r=m;}}returnl;}}/** * Your Router object will be instantiated and called as such: * Router obj = new Router(memoryLimit); * boolean param_1 = obj.addPacket(source,destination,timestamp); * int[] param_2 = obj.forwardPacket(); * int param_3 = obj.getCount(destination,startTime,endTime); */
classRouter{private:intlim;unordered_set<longlong>vis;deque<array<int,3>>q;unordered_map<int,int>idx;unordered_map<int,vector<int>>d;longlongf(inta,intb,intc){return((longlong)a<<46)|((longlong)b<<29)|(longlong)c;}public:Router(intmemoryLimit){lim=memoryLimit;}booladdPacket(intsource,intdestination,inttimestamp){longlongx=f(source,destination,timestamp);if(vis.count(x)){returnfalse;}vis.insert(x);if((int)q.size()>=lim){forwardPacket();}q.push_back({source,destination,timestamp});d[destination].push_back(timestamp);returntrue;}vector<int>forwardPacket(){if(q.empty()){return{};}autopacket=q.front();q.pop_front();ints=packet[0],d_=packet[1],t=packet[2];vis.erase(f(s,d_,t));idx[d_]++;return{s,d_,t};}intgetCount(intdestination,intstartTime,intendTime){auto&ls=d[destination];intk=idx[destination];autoi=lower_bound(ls.begin()+k,ls.end(),startTime);autoj=lower_bound(ls.begin()+k,ls.end(),endTime+1);returnj-i;}};/** * Your Router object will be instantiated and called as such: * Router* obj = new Router(memoryLimit); * bool param_1 = obj->addPacket(source,destination,timestamp); * vector<int> param_2 = obj->forwardPacket(); * int param_3 = obj->getCount(destination,startTime,endTime); */
typeRouterstruct{limintvismap[int64]struct{}q[][3]intidxmap[int]intdmap[int][]int}funcConstructor(memoryLimitint)Router{returnRouter{lim:memoryLimit,vis:make(map[int64]struct{}),q:make([][3]int,0),idx:make(map[int]int),d:make(map[int][]int),}}func(this*Router)f(a,b,cint)int64{returnint64(a)<<46|int64(b)<<29|int64(c)}func(this*Router)AddPacket(sourceint,destinationint,timestampint)bool{x:=this.f(source,destination,timestamp)if_,ok:=this.vis[x];ok{returnfalse}this.vis[x]=struct{}{}iflen(this.q)>=this.lim{this.ForwardPacket()}this.q=append(this.q,[3]int{source,destination,timestamp})this.d[destination]=append(this.d[destination],timestamp)returntrue}func(this*Router)ForwardPacket()[]int{iflen(this.q)==0{return[]int{}}packet:=this.q[0]this.q=this.q[1:]s,d,t:=packet[0],packet[1],packet[2]delete(this.vis,this.f(s,d,t))this.idx[d]++return[]int{s,d,t}}func(this*Router)GetCount(destinationint,startTimeint,endTimeint)int{ls:=this.d[destination]k:=this.idx[destination]i:=sort.Search(len(ls)-k,func(iint)bool{returnls[i+k]>=startTime})+kj:=sort.Search(len(ls)-k,func(iint)bool{returnls[i+k]>=endTime+1})+kreturnj-i}/** * Your Router object will be instantiated and called as such: * obj := Constructor(memoryLimit) * param_1 := obj.AddPacket(source,destination,timestamp) * param_2 := obj.ForwardPacket() * param_3 := obj.GetCount(destination,startTime,endTime) */
classRouter{privatelim:number;privatevis:Set<number>;privateq:[number,number,number][];privateidx:Map<number,number>;privated:Map<number,number[]>;constructor(memoryLimit:number){this.lim=memoryLimit;this.vis=newSet();this.q=[];this.idx=newMap();this.d=newMap();}privatef(a:number,b:number,c:number):number{return((BigInt(a)<<46n)|(BigInt(b)<<29n)|BigInt(c))asunknownasnumber;}addPacket(source:number,destination:number,timestamp:number):boolean{constx=this.f(source,destination,timestamp);if(this.vis.has(x)){returnfalse;}this.vis.add(x);if(this.q.length>=this.lim){this.forwardPacket();}this.q.push([source,destination,timestamp]);if(!this.d.has(destination)){this.d.set(destination,[]);}this.d.get(destination)!.push(timestamp);returntrue;}forwardPacket():number[]{if(this.q.length===0){return[];}const[s,d,t]=this.q.shift()!;this.vis.delete(this.f(s,d,t));this.idx.set(d,(this.idx.get(d)??0)+1);return[s,d,t];}getCount(destination:number,startTime:number,endTime:number):number{constls=this.d.get(destination)??[];constk=this.idx.get(destination)??0;consti=this.lowerBound(ls,startTime,k);constj=this.lowerBound(ls,endTime+1,k);returnj-i;}privatelowerBound(arr:number[],target:number,from:number):number{letl=from,r=arr.length;while(l<r){constm=Math.floor((l+r)/2);if(arr[m]<target){l=m+1;}else{r=m;}}returnl;}}/** * Your Router object will be instantiated and called as such: * var obj = new Router(memoryLimit) * var param_1 = obj.addPacket(source,destination,timestamp) * var param_2 = obj.forwardPacket() * var param_3 = obj.getCount(destination,startTime,endTime) */