Pattern #17

Queue

Important interview questions, thinking patterns, BFS queue mechanics, and rules for solving queue problems in Go.

Must Solve

15 core questions — solve these first.

  1. 1.Implement Queue using Stacks
    easy
  2. 2.Number of Recent Calls
    easy
  3. 3.Moving Average from Data Stream
    easy
  4. 4.Design Circular Queue
    medium
  5. 5.Rotting Oranges
    medium
  6. 6.Number of Islands
    medium
  7. 7.Binary Tree Level Order Traversal
    medium
  8. 8.Open the Lock
    medium
  9. 9.Shortest Path in Binary Matrix
    medium
  10. 10.Walls and Gates
    medium
  11. 11.Perfect Squares
    medium
  12. 12.Word Ladder
    hard
  13. 13.Snakes and Ladders
    medium
  14. 14.Dota2 Senate
    medium
  15. 15.Time Needed to Buy Tickets
    easy

Also Important

10 more questions worth practicing.

  1. 16.First Unique Character in a Stream
    medium
  2. 17.Reveal Cards In Increasing Order
    medium
  3. 18.Design Front Middle Back Queue
    medium
  4. 19.Task Scheduler
    medium
  5. 20.Jump Game III
    medium
  6. 21.Minimum Genetic Mutation
    medium
  7. 22.01 Matrix
    medium
  8. 23.As Far from Land as Possible
    medium
  9. 24.Shortest Bridge
    medium
  10. 25.Number of Provinces
    medium

How to Think

  1. Need first item first?Queue (FIFO)
  2. Need process things in arrival order?Queue
  3. Need shortest path with equal-cost moves?BFS + Queue
  4. Need level-by-level traversal?Queue
  5. Need process neighbors layer by layer?BFS
  6. Need newest item first?Stack (not Queue)

Go BFS Queue Template (Production Head Pointer Approach)

Efficient O(1) Amortized BFS Template

queue := []int{start}
visited := map[int]bool{start: true}
head := 0 // Avoids expensive slice re-allocations (queue = queue[1:])

for head < len(queue) {
    curr := queue[head]
    head++

    for _, next := range getNeighbors(curr) {
        if !visited[next] {
            visited[next] = true // Mark visited WHEN ENQUEUEING!
            queue = append(queue, next)
        }
    }
}

👉 Total Time: O(V + E) | Space: O(V)

Queue vs BFS & Circular Queue

Queue vs BFS
Queue = Data Structure
BFS   = Algorithm (uses Queue)

Queue stores the discovered nodes that BFS should visit next in arrival order.

Circular Queue
(index + 1) % capacity
Wraps around fixed array buffer

End connects back to beginning for fixed-size bounded memory buffers.

Visual Memory Rule
Enter BACK → → → → Exit FRONT
BFS Rule: Mark visited WHEN ENQUEUEING (prevents duplicate visits)
Tree Level: Process size := len(queue) before inner loop

💡 Golden Rule: "If the oldest waiting item should be handled first, think Queue."

Common Interview Mistakes

1. Using Stack Instead of Queue

Accidentally popping from the back (Stack/LIFO) turns BFS into DFS and ruins shortest path guarantees!

2. Marking Visited Too Late

Marking visited when DEQUEUEING instead of when ENQUEUEING causes identical nodes to be enqueued multiple times.

3. Forgetting Level Size in Level Order

In tree level-order traversal, compute size := len(queue) at level start to separate levels.

4. Dequeueing Empty Queue

Accessing queue[0] or queue[head] without checking length causes index out-of-bounds panic.

Interview Rules

  1. 1. Arrival order? → Queue
  2. 2. Oldest item first? → Queue
  3. 3. BFS? → Queue
  4. 4. Shortest path with equal edge cost? → BFS + Queue
  5. 5. Level order traversal? → Queue
  6. 6. Grid spreading problem? → BFS + Queue
  7. 7. Mark visited when enqueueing to prevent duplicate entries
  8. 8. Enqueue at back, dequeue from front
  9. 9. Go BFS optimization → Use head pointer index instead of queue[1:]

Small Rules

  1. Rule 1: Main operations Enqueue, Dequeue, Front/Peek are O(1).
  2. Rule 2: Queue processes items in first-in first-out (FIFO) arrival order.
  3. Rule 3: Always check len(queue) > 0 before removing from front.
  4. Rule 4: BFS almost always uses a Queue because oldest discovered nodes must be visited first.
  5. Rule 5: For BFS, mark visited immediately upon enqueueing to avoid duplicate work.

Production Thinking

Request ProcessingHTTP requests arrive & process in FIFO order (Request A -> B -> C)

Background Job WorkersImage resizing, email sending jobs wait in worker queues

Message StreamingKafka partitions & rabbitmq message queues deliver ordered events

Print QueuePrinter processes submitted documents in FIFO order

Rate & Sensor BuffersFixed-size circular queue for last 100 sensor readings with bounded memory

Remember This

First In                    → First Out
Add                         → Back
Remove                      → Front
BFS                         → Queue
Shortest unweighted path    → BFS + Queue
Tree levels                 → Queue
Grid spreading              → Queue
Fixed-size buffer           → Circular Queue

💡 Golden Rule: "If the oldest waiting item should be handled first, think Queue."