DSA Tutorial
🔍

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.

ProblemDifficultyRecognition ClueKey Insight
Binary Tree Level Order TraversalEasy"level by level", "level order"levelSize = queue.size() before inner loop
Binary Tree Right Side ViewMedium"rightmost node at each level"Last node dequeued per level is the rightmost
Average of Levels in Binary TreeEasy"average value at each depth"Sum all values per level, divide by levelSize
Minimum Depth of Binary TreeEasy"minimum depth", "nearest leaf"BFS finds nearest leaf — first leaf reached is answer
Maximum Width of Binary TreeMedium"width between leftmost and rightmost"Assign position indices; width = rightPos - leftPos + 1
Populating Next Right PointersMedium"connect nodes at same level"Use level-order; last node in each level points to null
Zigzag Level Order TraversalMedium"zigzag", "alternating left-right"Level flag: even→left-to-right, odd→right-to-left
N-ary Tree Level OrderEasy"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.

ProblemDifficultyRecognition ClueKey Insight
Rotting OrangesMedium"spread to neighbours each step, minimum time"Multi-source BFS from all rotten cells; count remaining fresh
01 MatrixMedium"distance to nearest 0"Multi-source BFS from all 0-cells simultaneously
Walls and GatesMedium"distance from each empty room to nearest gate"Multi-source BFS from all gates
Flood FillEasy"change colour of connected region"BFS from starting cell; enqueue same-colour neighbours
Number of IslandsMedium"count connected components"BFS marks each island; count BFS initiations
Pacific Atlantic Water FlowMedium"cells that can reach both oceans"Reverse BFS from each ocean boundary; intersect results
Shortest Path in Binary MatrixMedium"shortest path 0→0 in 0/1 grid"BFS from (0,0); move to 0-neighbours including diagonals
Jump Game IIIMedium"can you reach index with value 0"BFS from start; enqueue i+arr[i] and i-arr[i]
As Far from Land as PossibleMedium"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.

ProblemDifficultyRecognition ClueKey Insight
Word LadderHard"minimum transformations, one char at a time"Try all 26 substitutions at each position; BFS on word graph
Word Ladder IIHard"all shortest transformation sequences"BFS to build layer graph; DFS to enumerate all paths
Open the LockMedium"minimum turns on 4-dial combination lock"Each state is a 4-char string; 8 neighbours (±1 per wheel)
Minimum Genetic MutationMedium"minimum mutations from start to end gene"Same as Word Ladder but gene bank is the word list
Sliding PuzzleHard"minimum moves to solve 2×3 sliding puzzle"Serialize board as string; BFS on state strings
Bus RoutesHard"minimum buses to reach destination"BFS on routes, not stops; track which routes have been used
Escape the Spreading FireHard"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).

ProblemDifficultyRecognition ClueKey Insight
Sliding Window MaximumHard"maximum in each window of size k"Monotonic decreasing deque; front = max; pop back when smaller
Sliding Window MinimumHard"minimum in each window of size k"Monotonic increasing deque; front = min; pop back when larger
Constrained Subsequence SumHard"maximum sum, no two elements more than k apart"DP + monotonic deque for O(n) max over window
Jump Game VIMedium"max score jumping at most k steps"DP + max deque of window k: dp[i] = nums[i] + maxDeque.front()
Longest Subarray with Absolute Diff ≤ LimitHard"subarray where max-min ≤ limit"Two deques (max and min); shrink left when diff > limit
Maximum of All Subarrays of Size kMedium"print max of every contiguous subarray of size k"Classic monotonic deque problem
Sum of Subarray MinimumsHard"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.

ProblemDifficultyRecognition ClueKey Insight
Kth Largest Element in ArrayMedium"k-th largest"Min-heap of size k; top = k-th largest
K Closest Points to OriginMedium"k closest points"Max-heap of size k by distance; top = farthest among k closest
Top K Frequent ElementsMedium"k most frequent"Frequency map + min-heap of size k by frequency
Merge K Sorted ListsHard"merge k sorted linked lists"Min-heap of (val, list pointer); always pop global min
Find Median from Data StreamHard"insert numbers, query median at any point"Max-heap (lower half) + min-heap (upper half); balance sizes
Kth Smallest Element in Sorted MatrixMedium"k-th smallest in row/col sorted matrix"Min-heap seeded with first column; pop k times
Task SchedulerMedium"minimum intervals to finish tasks with cooldown"Max-heap by frequency; cooldown simulation with idle slots
Meeting Rooms IIMedium"minimum conference rooms needed"Sort by start; min-heap of end times — earliest ending room
Reorganize StringMedium"rearrange so no two adjacent chars same"Max-heap by frequency; alternate two most-frequent
Dijkstra's AlgorithmMedium"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.

ProblemDifficultyRecognition ClueKey Insight
Implement Queue using StacksEasy"build FIFO using two LIFO stacks"Inbox stack + outbox stack; lazy transfer on dequeue
Implement Stack using QueuesEasy"build LIFO using FIFO queues"On push, rotate new element to front — O(n) push, O(1) pop
Design Circular QueueMedium"circular buffer, enQueue/deQueue/Front/Rear/isEmpty/isFull"front, rear, size; isEmpty: size==0; isFull: size==capacity
Design Circular DequeMedium"circular double-ended queue"Extend circular queue with addFront/deleteLast/getFront/getRear
Design Hit CounterMedium"count hits in last 300 seconds"Queue of timestamps; remove expired (>300s old) before counting
Moving Average from Data StreamEasy"average of last k numbers in stream"Queue of size k; maintain running sum; add new, remove oldest
Design Recent Calls CounterEasy"how many calls in last 3000ms"Queue of timestamps; popleft while front < t-3000
Design Front Middle Back QueueHard"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 ProblemPatternData Structure
"level order", "each depth", "layer by layer"Tree BFSQueue
"minimum steps/hops to reach"Single-source BFSQueue
"distance to nearest [source]"Multi-source BFSQueue
"spread to neighbours each step"Multi-source grid BFSQueue
"minimum transformations", "one change at a time"Implicit BFSQueue
"maximum in sliding window of size k"Monotonic dequeDeque
"k-th largest/smallest"Min/max heapPriority Queue
"k closest", "k most frequent"Fixed-size heapPriority Queue
"merge sorted", "always global minimum"Min-heapPriority Queue
"median from data stream"Two heapsPriority Queue ×2
"implement X using Y"Queue designTwo stacks / circular array
"circular buffer", "enQueue/deQueue/Front/Rear"Circular queueCircular array
"sliding window count", "hits in last N seconds"Time-windowed queueQueue + expiry

Difficulty Progression Reference

StageCharacteristicsRepresentative Problems
FoundationSingle BFS pass, no additional stateLevel Order, Flood Fill, Number of Islands
Early IntermediateLevel boundaries, multi-source seedingRight Side View, Rotting Oranges, 01 Matrix
IntermediateImplicit graphs, priority queue basicsWord Ladder, Kth Largest, K Closest Points
Late IntermediateCombined BFS+state, DP+deque, multi-heapOpen the Lock, Task Scheduler, Find Median
AdvancedMulti-source + constraint, complex state BFSBus 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:

  1. Pattern — which of the 6 patterns does this belong to?
  2. Data structure — plain queue, deque, priority queue, or circular queue?
  3. Recognition clue — what phrase triggered this pattern?
  4. BFS variant — single-source, multi-source, or implicit graph?
  5. Edge case missed — empty grid? Unreachable target? k > n?
  6. 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.

Suggested Quiz

A problem asks for the 'minimum steps to reach a target'. Which data structure should you reach for first?

1/6
Queue Practice Problems