The canteen token lineline 1
  1. import collections
  2. q = collections.deque()
  3. q.append(101)
  4. q.append(102)
  5. q.append(103)
  6. served = q.popleft()
  7. served = q.popleft()
  8. print(q[0], "still waits")

Variables

None yet

Load collections. It has deque, Python's fast queue.

Step 1 of 8

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.

10110210310410501234
before pop(0)
1021031041050123
after pop(0): four items moved left

So pop(0) is O(n). A collections.deque tracks both ends directly, so append and popleft are both O(1), and nothing shifts.

Operationdequelist
Add at backappend, O(1)append, O(1)
Remove frontpopleft, O(1)pop(0), O(n)
Look at frontq[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.

Serve until emptyline 1
Try another n
  1. import collections
  2. n = 3
  3. q = collections.deque()
  4. for t in range(n):
  5. q.append(101 + t)
  6. while q:
  7. tok = q.popleft()
  8. print("Serve", tok)
  9. print("Line empty")

Variables

None yet

Line 1 runs.

Step 1 of 21

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.

Visualizer

Queue

Open full →

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.

Number of Recent Callsline 1
Try another w
  1. import collections
  2. w = 3000
  3. times = [1, 100, 3001, 3002]
  4. q = collections.deque()
  5. for t in times:
  6. q.append(t)
  7. while q[0] < t - w:
  8. q.popleft()
  9. print(t, "->", len(q))

Variables

None yet

Line 1 runs.

Step 1 of 23

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.

Queue with two stacksline 1
  1. ins, out = [], []
  2. for x in [1, 2, 3]:
  3. ins.append(x)
  4. if not out:
  5. while ins:
  6. out.append(ins.pop())
  7. print(out.pop())
  8. ins.append(4)
  9. print(out.pop())

Variables

ins
[] (just changed)
out
[] (just changed)

Two empty stacks: ins for new, out for leaving.

Step 1 of 19

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.

502030400123
capacity 4: head 1, tail 1, full

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)
RemovesThe oldestThe newest
LikeCanteen linePile of plates
Used forPrinter jobs, IRCTC waiting list, BFSUndo, 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.