Queue Practice Problems
How to Use This Problem List
Queue problems separate cleanly into six patterns. The queue is always the right structure when you need to process things in arrival order — but the variant (plain queue, deque, priority queue, circular queue) determines which interview technique applies.
Practice by pattern — solve four or five problems from one pattern before moving to the next. After a week of this, the question "what structure does this need?" becomes automatic.
For each problem: name the pattern within two minutes of reading. The recognition clue column tells you the exact phrase that triggers the technique.
Pattern 1: Basic BFS — Shortest Path and Level Order
The fundamental use of a queue in graph and tree problems. FIFO ordering guarantees level-by-level exploration, which gives shortest-path guarantees in unweighted settings.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Binary Tree Level Order Traversal | Easy | "level by level", "level order" | levelSize = queue.size() before inner loop |
| Binary Tree Right Side View | Medium | "rightmost node at each level" | Last node dequeued per level is the rightmost |
| Average of Levels in Binary Tree | Easy | "average value at each depth" | Sum all values per level, divide by levelSize |
| Minimum Depth of Binary Tree | Easy | "minimum depth", "nearest leaf" | BFS finds nearest leaf — first leaf reached is answer |
| Maximum Width of Binary Tree | Medium | "width between leftmost and rightmost" | Assign position indices; width = rightPos - leftPos + 1 |
| Populating Next Right Pointers | Medium | "connect nodes at same level" | Use level-order; last node in each level points to null |
| Zigzag Level Order Traversal | Medium | "zigzag", "alternating left-right" | Level flag: even→left-to-right, odd→right-to-left |
| N-ary Tree Level Order | Easy | "N-ary tree", "general tree BFS" | Same as binary but enqueue all children |
Complexity target: O(n) time, O(w) space where w = maximum level width.
Recognition signal: "level", "depth", "layer", "each row", "nearest", "minimum hops". The problem involves a tree or graph where arrival order equals depth order.
Pattern 2: BFS on Grids — Multi-Source and Flood Fill
BFS on a 2D matrix where cells are nodes and adjacent cells are neighbours. Multi-source BFS seeds multiple starting cells simultaneously and finds minimum distances in a single pass.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Rotting Oranges | Medium | "spread to neighbours each step, minimum time" | Multi-source BFS from all rotten cells; count remaining fresh |
| 01 Matrix | Medium | "distance to nearest 0" | Multi-source BFS from all 0-cells simultaneously |
| Walls and Gates | Medium | "distance from each empty room to nearest gate" | Multi-source BFS from all gates |
| Flood Fill | Easy | "change colour of connected region" | BFS from starting cell; enqueue same-colour neighbours |
| Number of Islands | Medium | "count connected components" | BFS marks each island; count BFS initiations |
| Pacific Atlantic Water Flow | Medium | "cells that can reach both oceans" | Reverse BFS from each ocean boundary; intersect results |
| Shortest Path in Binary Matrix | Medium | "shortest path 0→0 in 0/1 grid" | BFS from (0,0); move to 0-neighbours including diagonals |
| Jump Game III | Medium | "can you reach index with value 0" | BFS from start; enqueue i+arr[i] and i-arr[i] |
| As Far from Land as Possible | Medium | "find water cell farthest from any land" | Multi-source BFS from all land cells; max distance found |
Complexity target: O(rows × cols) time and space.
Recognition signal: "grid", "matrix", "spread", "adjacent cells", "distance to nearest", "flood fill". Any time the problem involves propagation across a 2D grid.
Pattern 3: BFS on Implicit Graphs — Word Problems and State Spaces
The graph is not given explicitly — nodes are states (words, numbers, configurations) and edges are valid single-step transformations. BFS finds the fewest transformations to reach the target state.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Word Ladder | Hard | "minimum transformations, one char at a time" | Try all 26 substitutions at each position; BFS on word graph |
| Word Ladder II | Hard | "all shortest transformation sequences" | BFS to build layer graph; DFS to enumerate all paths |
| Open the Lock | Medium | "minimum turns on 4-dial combination lock" | Each state is a 4-char string; 8 neighbours (±1 per wheel) |
| Minimum Genetic Mutation | Medium | "minimum mutations from start to end gene" | Same as Word Ladder but gene bank is the word list |
| Sliding Puzzle | Hard | "minimum moves to solve 2×3 sliding puzzle" | Serialize board as string; BFS on state strings |
| Bus Routes | Hard | "minimum buses to reach destination" | BFS on routes, not stops; track which routes have been used |
| Escape the Spreading Fire | Hard | "latest safe start time to escape" | Binary search on start time + multi-source BFS for fire spread |
Complexity target: O(N × M × 26) for word-type problems (N words, M characters). O(states) for state-space BFS.
Recognition signal: "minimum transformations", "minimum steps from state A to state B", "each step changes one thing". The problem has a well-defined start state, end state, and set of valid transitions.
Pattern 4: Sliding Window Deque — Monotonic Queue
A deque (double-ended queue) maintains a monotonic sequence of candidates. The front is always the current window's answer. Elements expire from the front (window slides); dominated elements are removed from the back (maintain monotonicity).
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Sliding Window Maximum | Hard | "maximum in each window of size k" | Monotonic decreasing deque; front = max; pop back when smaller |
| Sliding Window Minimum | Hard | "minimum in each window of size k" | Monotonic increasing deque; front = min; pop back when larger |
| Constrained Subsequence Sum | Hard | "maximum sum, no two elements more than k apart" | DP + monotonic deque for O(n) max over window |
| Jump Game VI | Medium | "max score jumping at most k steps" | DP + max deque of window k: dp[i] = nums[i] + maxDeque.front() |
| Longest Subarray with Absolute Diff ≤ Limit | Hard | "subarray where max-min ≤ limit" | Two deques (max and min); shrink left when diff > limit |
| Maximum of All Subarrays of Size k | Medium | "print max of every contiguous subarray of size k" | Classic monotonic deque problem |
| Sum of Subarray Minimums | Hard | "sum of minimums of all subarrays" | Monotonic stack (left/right nearest smaller) — deque variant |
Complexity target: O(n) time, O(k) space.
Recognition signal: "maximum/minimum in every window of size k", "sliding window with extreme query". The constraint is a fixed-size window and the query is always max or min within it.
Pattern 5: Priority Queue — Greedy Order Processing
Use a heap-backed priority queue when the problem requires always processing the most/least urgent element — not the first-arrived. The heap provides O(log n) extraction of the global minimum or maximum.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Kth Largest Element in Array | Medium | "k-th largest" | Min-heap of size k; top = k-th largest |
| K Closest Points to Origin | Medium | "k closest points" | Max-heap of size k by distance; top = farthest among k closest |
| Top K Frequent Elements | Medium | "k most frequent" | Frequency map + min-heap of size k by frequency |
| Merge K Sorted Lists | Hard | "merge k sorted linked lists" | Min-heap of (val, list pointer); always pop global min |
| Find Median from Data Stream | Hard | "insert numbers, query median at any point" | Max-heap (lower half) + min-heap (upper half); balance sizes |
| Kth Smallest Element in Sorted Matrix | Medium | "k-th smallest in row/col sorted matrix" | Min-heap seeded with first column; pop k times |
| Task Scheduler | Medium | "minimum intervals to finish tasks with cooldown" | Max-heap by frequency; cooldown simulation with idle slots |
| Meeting Rooms II | Medium | "minimum conference rooms needed" | Sort by start; min-heap of end times — earliest ending room |
| Reorganize String | Medium | "rearrange so no two adjacent chars same" | Max-heap by frequency; alternate two most-frequent |
| Dijkstra's Algorithm | Medium | "shortest path in weighted graph" | Min-heap of (dist, node); lazy deletion of stale entries |
Complexity target: O(n log k) for k-element heap problems, O((V+E) log V) for Dijkstra.
Recognition signal: "k-th largest/smallest", "k closest", "k most frequent", "merge sorted", "median of stream", "minimum cost/distance". Any problem requiring repeated access to the globally smallest or largest element from a dynamic collection.
Pattern 6: Queue Design — Implement and Extend
Design problems that test whether you understand the internal mechanics of queues — implementing one structure using another, or extending a queue with additional O(1) capabilities.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Implement Queue using Stacks | Easy | "build FIFO using two LIFO stacks" | Inbox stack + outbox stack; lazy transfer on dequeue |
| Implement Stack using Queues | Easy | "build LIFO using FIFO queues" | On push, rotate new element to front — O(n) push, O(1) pop |
| Design Circular Queue | Medium | "circular buffer, enQueue/deQueue/Front/Rear/isEmpty/isFull" | front, rear, size; isEmpty: size==0; isFull: size==capacity |
| Design Circular Deque | Medium | "circular double-ended queue" | Extend circular queue with addFront/deleteLast/getFront/getRear |
| Design Hit Counter | Medium | "count hits in last 300 seconds" | Queue of timestamps; remove expired (>300s old) before counting |
| Moving Average from Data Stream | Easy | "average of last k numbers in stream" | Queue of size k; maintain running sum; add new, remove oldest |
| Design Recent Calls Counter | Easy | "how many calls in last 3000ms" | Queue of timestamps; popleft while front < t-3000 |
| Design Front Middle Back Queue | Hard | "push/pop at front, back, and middle in O(1)" | Two deques of equal size; rebalance after each operation |
Complexity target: O(1) amortized for all core operations where possible.
Recognition signal: "implement X using Y", "O(1) for all operations", "sliding time window count", "circular buffer with fixed capacity". The problem tests mechanics rather than algorithms.
Recommended Study Order
Week 1 — BFS Foundations Pattern 1 (Tree BFS): Level Order, Right Side View, Minimum Depth Pattern 2 (Grid BFS): Number of Islands, Flood Fill, Rotting Oranges Week 2 — BFS Extensions Pattern 2 (Multi-source): 01 Matrix, Walls and Gates Pattern 3 (Implicit BFS): Word Ladder, Open the Lock Week 3 — Advanced Data Structures Pattern 4 (Monotonic Deque): Sliding Window Max, Jump Game VI Pattern 5 (Priority Queue): Kth Largest, K Closest, Merge K Sorted Week 4 — Design and Hard Problems Pattern 6 (Design): Implement Queue Using Stacks, Design Circular Queue Pattern 5 (Hard): Find Median from Data Stream, Task Scheduler Pattern 3 (Hard): Bus Routes, Sliding Puzzle Revisit any pattern that felt unclear
Problem-Solving Checklist for Queue Problems
Before writing code, run through this for every queue problem:
1. Is this a pure ordering/scheduling problem? → Arrival order matters → plain Queue (FIFO) → Priority matters, not arrival → Priority Queue (heap) → Both ends of a window matter → Deque → Fixed-size buffer with wrap-around → Circular Queue 2. Is this a BFS problem? → Shortest path, fewest steps → single-source BFS + queue → Distance from multiple sources → multi-source BFS → Minimum transformations between states → implicit BFS → Weighted graph → Dijkstra (priority queue replaces plain queue) 3. For grid BFS: → Define neighbours (4-directional or 8-directional?) → Visited condition (mark cell value OR use separate visited matrix?) → Multi-source? Seed ALL source cells before starting BFS 4. For priority queue: → Min-heap or max-heap? → k-th largest/smallest → use OPPOSITE heap type (k-th largest needs min-heap) → Fixed-size k? Maintain heap at exactly size k 5. For monotonic deque: → Store INDICES (not values) — expiry check needs position → Expiry: front index < i - k + 1 → pop from front → Monotonic property: back violates order for new element → pop from back 6. Edge cases: → Empty input → return 0, [], or -1 depending on problem → Single cell/node → trivially the answer → Target unreachable → return -1 or 0 → k > n for k-th problems → undefined/invalid input
Pattern Recognition Quick Reference
| Signal in Problem | Pattern | Data Structure |
|---|---|---|
| "level order", "each depth", "layer by layer" | Tree BFS | Queue |
| "minimum steps/hops to reach" | Single-source BFS | Queue |
| "distance to nearest [source]" | Multi-source BFS | Queue |
| "spread to neighbours each step" | Multi-source grid BFS | Queue |
| "minimum transformations", "one change at a time" | Implicit BFS | Queue |
| "maximum in sliding window of size k" | Monotonic deque | Deque |
| "k-th largest/smallest" | Min/max heap | Priority Queue |
| "k closest", "k most frequent" | Fixed-size heap | Priority Queue |
| "merge sorted", "always global minimum" | Min-heap | Priority Queue |
| "median from data stream" | Two heaps | Priority Queue ×2 |
| "implement X using Y" | Queue design | Two stacks / circular array |
| "circular buffer", "enQueue/deQueue/Front/Rear" | Circular queue | Circular array |
| "sliding window count", "hits in last N seconds" | Time-windowed queue | Queue + expiry |
Difficulty Progression Reference
| Stage | Characteristics | Representative Problems |
|---|---|---|
| Foundation | Single BFS pass, no additional state | Level Order, Flood Fill, Number of Islands |
| Early Intermediate | Level boundaries, multi-source seeding | Right Side View, Rotting Oranges, 01 Matrix |
| Intermediate | Implicit graphs, priority queue basics | Word Ladder, Kth Largest, K Closest Points |
| Late Intermediate | Combined BFS+state, DP+deque, multi-heap | Open the Lock, Task Scheduler, Find Median |
| Advanced | Multi-source + constraint, complex state BFS | Bus Routes, Sliding Puzzle, Escape the Fire |
Common Interview Topics by Company Focus
Product-based companies (FAANG-tier):
- ›BFS shortest path and level-order — always in rotation
- ›Rotting Oranges and 01 Matrix — multi-source BFS standards
- ›Find Median from Data Stream — two-heap design
- ›Sliding Window Maximum — monotonic deque
- ›Merge K Sorted Lists — priority queue must-know
- ›Word Ladder — implicit BFS on a word graph
Service-based and on-campus:
- ›Number of Islands, Level Order, BFS traversals
- ›Kth Largest, Top K Frequent — priority queue basics
- ›Implement Queue using Stacks — design understanding
Startup and mid-size tech:
- ›Moving Average, Hit Counter — time-windowed queue
- ›Task Scheduler — practical priority queue
- ›K Closest Points — geometric priority queue
Progress Tracking
After solving each problem, record:
- ›Pattern — which of the 6 patterns does this belong to?
- ›Data structure — plain queue, deque, priority queue, or circular queue?
- ›Recognition clue — what phrase triggered this pattern?
- ›BFS variant — single-source, multi-source, or implicit graph?
- ›Edge case missed — empty grid? Unreachable target? k > n?
- ›Time to solve — target 20-25 minutes for medium problems under interview conditions
After 30 problems across all six patterns, the structure should become reflexive — "multi-source grid BFS" should be your first thought when you see "minimum time for something to spread across a matrix," before you have finished reading the problem.
A problem asks for the 'minimum steps to reach a target'. Which data structure should you reach for first?