- import collections
- q = collections.deque()
- q.append(101)
- q.append(102)
- q.append(103)
- served = q.popleft()
- served = q.popleft()
- print(q[0], "still waits")
Variables
None yet
Load collections. It has deque, Python's fast queue.
That was a queue: items join at the back and leave from the front, so the first in is the first out (FIFO). A deque (say "deck") gives you append for the back and popleft for the front.
Quick check
Quick check: Token 104 joins the line now. Who is served next?
Why not a plain list?#
A Python list keeps its items in a row of cells starting at index 0. list.pop(0) removes the first cell, and then every other item must shift one cell left to fill the gap.
So pop(0) is O(n). A collections.deque tracks both ends directly, so append and popleft are both O(1), and nothing shifts.
| Operation | deque | list |
|---|---|---|
| Add at back | append, O(1) | append, O(1) |
| Remove front | popleft, O(1) | pop(0), O(n) |
| Look at front | q[0], O(1) | a[0], O(1) |
Quick check
Quick check: A list holds 1 lakh IRCTC tatkal requests. How many items move on one pop(0)?
Serving until the line is empty#
This is the core loop: fill the queue, then serve the front while anyone is waiting. while q: is true only when the queue has items, because an empty deque or list counts as False in Python. Slide n to 0 and to 1 to see the edge cases.
n- import collections
- n = 3
- q = collections.deque()
- for t in range(n):
- q.append(101 + t)
- while q:
- tok = q.popleft()
- print("Serve", tok)
- print("Line empty")
Variables
None yet
Line 1 runs.
With n = 0 the queue starts empty, while q: is false at once, and popleft never runs.
Quick check
Quick check: The queue is empty and you call q.popleft() without checking. What happens?
Now play with a queue yourself. It starts with 10, 20, 30 and plays one dequeue: watch 10 leave first because it arrived first.
A sliding time window#
Number of Recent Calls: ping(t) is called each time a request arrives, at time t milliseconds (ms), and t always grows. Return how many requests came from t - 3000 to t. Old times sit at the front, so add t at the back and drop times older than t - 3000 from the front. Slide w to try a smaller window.
w- import collections
- w = 3000
- times = [1, 100, 3001, 3002]
- q = collections.deque()
- for t in times:
- q.append(t)
- while q[0] < t - w:
- q.popleft()
- print(t, "->", len(q))
Variables
None yet
Line 1 runs.
In the problem, q lives in a RecentCounter class and lines 6 to 9 are the body of ping(t), which returns len(q). q[0] is safe inside the while: the new time t was just added and is never older than t - w, so the queue cannot become empty there.
Quick check
Quick check: After those four calls the queue is [100, 3001, 3002]. Now ping(6003) arrives. What is returned?
A queue from two stacks#
A stack only touches its top. Two stacks can still act as a queue. New items go on ins. To dequeue, pop from out. Only when out is empty, move everything from ins to out: the full move reverses the order, so the oldest item lands on top.
- ins, out = [], []
- for x in [1, 2, 3]:
- ins.append(x)
- if not out:
- while ins:
- out.append(ins.pop())
- print(out.pop())
- ins.append(4)
- print(out.pop())
Variables
- ins
- [] (just changed)
- out
- [] (just changed)
Two empty stacks: ins for new, out for leaving.
One dequeue can move n items, so it is O(n) on its own. But each item is moved only once in its life: pushed on ins, moved to out, popped. That is at most 4 list operations per item (push on ins, pop from ins, push on out, pop from out), so n items cost at most 4n in total: amortised O(1) per operation. peek works like dequeue but returns out[-1] without popping. The queue is empty only when both ins and out are empty.
Quick check
Quick check: 100 enqueues, then 100 dequeues. How many items move from ins to out in total?
The circular queue#
A circular queue (or ring buffer) uses a fixed array and two indexes: head for the front and tail for the next free cell. Nothing shifts. When an index passes the end, it wraps to 0 with (i + 1) % capacity. Capacity 4: 10, 20, 30, 40 were added, 10 was removed, then 50 went into index 0. Now head is 1 (20) and tail is (0 + 1) % 4 = 1. The array is full, and head equals tail, just as when it is empty, so real code also keeps a count.
Quick check
Quick check: Capacity is 5 and tail is at index 4. After one more enqueue, where is tail?
Queue or stack?#
| Queue (FIFO) | Stack (LIFO) | |
|---|---|---|
| Removes | The oldest | The newest |
| Like | Canteen line | Pile of plates |
| Used for | Printer jobs, IRCTC waiting list, BFS | Undo, brackets, DFS |
Anything served in arrival order is a queue. BFS and DFS both come later on the roadmap: BFS uses a queue to visit a graph level by level.
Quick check
Quick check: Your hostel printer gets jobs from 5 students. Which structure decides the print order?
The same queue in five languages#
Here is a full queue class in Python, C++, C, Java and Go.
One last check#
Quick check
Quick check: A two-stack queue starts empty. Enqueue 1, enqueue 2, dequeue, enqueue 3, dequeue. What does the second dequeue return, and how many items moved from ins to out in total?
Next is the Queue Operations visualizer, where you run enqueue and dequeue yourself before solving Number of Recent Calls with the window you built here.