First in line eats first
Queues as Lunch Lines
The analogy
The lunch line is fair: whoever arrived first gets served first, and new people join at the back. Nobody cuts in. That is a queue โ add at one end, remove from the other.
Visualizer
The lunch line
step 1 / 12frontemptyback
An empty lunch line. Two ends that do different jobs: you join at the back, you are served at the front.empty
๐ In depth โ the full reference
Queue operations โ all of them
| operation | meaning | cost (proper queue) |
|---|---|---|
| enqueue(x) | join at the back | O(1) |
| dequeue() | serve from the front | O(1) |
| peek front | who is next? | O(1) |
| isEmpty | anyone waiting? | O(1) |
Variants you will meet
- Deque (double-ended queue): O(1) at BOTH ends โ the sliding-window pattern in Module 7 depends on it.
- Circular buffer: a fixed array + two wrapping indexes (head % size, tail % size) โ the % operator from Module 0 doing production work in every audio driver and network card.
- Priority queue: serves the most URGENT, not the oldest โ that is a heap, Module 5.
- BFS (Module 3) is a queue-driven walk โ the queue IS what makes it explore ring by ring.
Python: deque, never list.pop(0)
from collections import deque
q = deque()
q.append("Ada") # enqueue โ O(1)
q.append("Bo")
first = q[0] # peek โ O(1)
served = q.popleft() # dequeue โ O(1) <- the whole point
# The trap: list.pop(0) shifts every element โ O(n) per serve,
# O(n^2) to drain. queue.Queue is for threads, not algorithms.from collections import deque
q = deque()
q.append("Ada") # join the back
q.append("Bo")
q.popleft() # "Ada" โ first in, first out
# never use list.pop(0) โ that is O(n)Check yourself
Enqueue A, B, C then dequeue. What comes out?
Practice โ write it yourself
serve(queue, k) serves the first k people FIFO-style: return [served_list, remaining_list] without mutating the input.
Python 3 ยท runs in your browser ยท your draft is saved locally
๐ My notessaved in this browser