Queues
First in, first out - handle things in the order they arrived.
- active this step
- removed / popped
ping(1)
The queue is [1]. Nothing is older than 1 − 3000, so it returns 1.
VARIABLES
- t
- 1
- q
- [1]
- returns
- 1
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A queue adds at the back and removes from the front. In Python, collections.deque gives O(1) operations at both ends.
Why it matters
Scheduling, buffering and breadth-first search all depend on handling the oldest item first.
Think of it like this
A line at a ticket counter: whoever arrived first is served first.
Use it when
- Processing items in arrival order
- Level-by-level traversal (BFS)
- Time windows over a stream of events
Avoid it when
- You need the most recent item first - use a stack
- You need the smallest item first - use a heap
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Enqueue (append) | O(1) | O(1) |
| Dequeue (popleft) | O(1) | O(1) |
| list.pop(0) instead | O(n) | O(1) |
Often confused with: priority queues - they serve by priority, not by arrival time.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- list.pop(0) is O(n); deque.popleft() is O(1)
- Time-window counters often keep a queue of timestamps
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Using list.pop(0) - every dequeue shifts the whole list
- Reading q[0] on an empty queue
- Mixing up which end you add to and remove from
Edge cases to test
- An empty queue before the first operation
- Many items expiring at once
- Equal timestamps
Knowledge check
Quick check to lock in the intuition.
Which Python structure removes from the front in O(1)?
Practice
Apply what you just watched on real interview problems.