# Program to check number of requests that will be processed with given conditions in python

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 −

• last := an empty map
• total := empty double ended queue
• windowtime := 60
• sort requests based on time, if they are same then sort based on uid
• amount := 0
• for each r in requests, do
• [uid, time] := r
• while size of total > 0 and total[0] + windowtime <= time, do
• delete left item of total
• while size of last[uid] > 0 and last[uid, 0] + windowtime <= time, do
• delete left item from last[uid]
• if size of total < g and size of last[uid] < u, then
• insert time at the end of last[uid]
• insert time at the end of total
• amount := amount + 1
• return amount

Let us see the following implementation to get better understanding −

## Example

Live Demo

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[1], x[0]])

amount = 0
for r in requests:
uid, time = r

while len(total) > 0 and total[0] + windowtime <= time:
total.popleft()

while len(last[uid]) > 0 and last[uid][0] + 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))

## Input

[[0, 1],[1, 2],[1,3]], 1, 5

## Output

2

Updated on: 03-Dec-2020

255 Views

##### Kickstart Your Career

Get certified by completing the course