synopsis · Linear patterns · chapter 17
Queues & Deques
10 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A queue is FIFO: offer at the rear, poll from the front — whoever waited longest leaves first. A deque opens both ends.
- use it when
"In arrival order", BFS / fewest steps, "in the last X seconds", rotation games, and the max or min of every window.
- template
Deque<Integer> q = new ArrayDeque<>();→offer,poll,peek,isEmpty. The same object is a stack withpush/pop/peek. - cost
offer / poll / peek: O(1) (amortized when ArrayDeque grows).
ArrayList.remove(0)is O(n), so n dequeues become O(n²). - template
Ring buffer:
head+size. Next free =(head + size) % k, rear =(head + size − 1) % k, dequeue =head = (head + 1) % k. - trap
head == tailmeans both empty and full — keep asize. Stepping left?(head − 1 + k) % k, because Java's%can be negative. - trap
Monotonic deque: store indices, not values — otherwise you can't tell when the front has left the window.
- cost
Monotonic deque and two-stack queue: each element goes in once and comes out at most once → O(n) total, amortized O(1) each.
- pro tip
Time window with growing timestamps? Offer the new one, poll expired ones from the front; the answer is the size.
- trap
poll()on an empty queue returns null —int x = q.poll();then throws. AndArrayDequerefusesnullelements.
Shaky on a card? Open the chapter or flip its recall cards.