14/32
Part 4 of 6 · Deques and rate limitsLearn and do

A deque holds a window you can't index

The practice problem's second level asks for the clients seen again within the last k requests. The log is a live stream: a generator you can walk once. You can't read keys[right - k] from a stream. You have to keep the last k keys yourself, adding at one end and removing from the other.

The third level, a rate limiter, goes further. It allows at most limit requests per client in any window seconds. So the window is measured in seconds, and how many entries it holds depends on the traffic.

Both need a queue: add at the back, take from the front.

A list takes from the front in O(n), a deque in O(1)

Here's what taking the first item does in each:

Taking the first item out
list.pop(0)
abcde
deque.popleft()
abcde

Red leaves. In the list, the 4 orange items behind it each move one place. In the deque, nothing else moves.

A Python list keeps its items side by side. Take the first one, and every item behind it shifts down one place. collections.deque, a double-ended queue, is built for both ends. Taking from its front moves nothing else.

Draining one of each:

Itemslist.pop(0) until emptydeque.popleft() until empty
100,0000.785 s2.9 ms
200,0003.153 s6.4 ms

Double the items and the list takes four times as long: O(n) per pop, O(n²) to drain. The deque's time doubles: O(1) per pop.

Three calls do the work here:

  • append(x) adds at the right.
  • popleft() takes from the left.
  • d[0] reads the oldest item without removing it.

Level 2's log arrives as a generator. Write last_k, which reads stream once and keeps only its last k keys in a deque.