Suppose we have a list of requests where each list contains elements like [uid, time_sec] (uid is the user id and time_sec is the timestamp). This indicates the user whose id is uid has requested to a website at timestamp time_sec. We also have two values u and g where u denotes maximum number of requests that are allowed in any < 60 second frame for a given uid and g is the maximum number of requests that are allowed in any < 60 second frame globally. Now if we want to process each request one by one and rate limit them. And if there are requests at the same time by multiple users, the requests with lower uid will be processed first, otherwise that request will be dropped. We have to find the total number of requests that will be processed successfully.
So, if the input is like requests = [[0, 1],[1, 2],[1,3]] u = 1 g = 5, then the output will be 2, as user 0 and 1 can send at time 1 and 2, but the second request from user 1 will not be processed as one user can send at most 1 request in 60 secs frame.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
from collections import defaultdict, deque class Solution: def solve(self, requests, u, g): last = defaultdict(deque) total = deque() windowtime = 60 requests.sort(key=lambda x: [x, x]) amount = 0 for r in requests: uid, time = r while len(total) > 0 and total + windowtime <= time: total.popleft() while len(last[uid]) > 0 and last[uid] + windowtime <= time: last[uid].popleft() if len(total) < g and len(last[uid]) < u: last[uid].append(time) total.append(time) amount += 1 return amount ob = Solution() requests = [[0, 1],[1, 2],[1,3]] u = 1 g = 5 print(ob.solve(requests, u, g))
[[0, 1],[1, 2],[1,3]], 1, 5