Rotting Oranges - Breadth-First Search Pattern

Rotting Oranges in Java using the Breadth-First Search pattern: problem statement, approach, template, complexity, and interview tips.

Rotting Oranges

Problem Statement

Return the minimum minutes until no fresh orange remains in a grid, or -1 if that is impossible.

Explore nodes level by level using a queue, which finds the shortest path in unweighted graphs.

Use this pattern when you need level order, the minimum number of steps, or the shortest transformation in an unweighted structure.

Approach

  1. Enqueue the start node(s) and mark them visited.
  2. Process one full level at a time using the queue size.
  3. Enqueue unvisited neighbours and count levels as steps.

Pattern Template (Java)

Queue<Node> queue = new ArrayDeque<>();
queue.offer(start);
while (!queue.isEmpty()) {
    int size = queue.size();
    for (int i = 0; i < size; i++) {
        Node cur = queue.poll();
        // process cur and enqueue its unvisited neighbours
    }
    // one level finished
}

Adapt this template to the exact rules of Rotting Oranges: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(V + E) time and O(V) space.

Interview Tips

  • Mark nodes visited when enqueuing, not when dequeuing.
  • Start from all sources at once for multi-source problems such as rotting oranges.
  • Start with a brute-force idea, state its complexity, then explain how the Breadth-First Search pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Previous: Binary Tree Level Order Traversal | Next: Word Ladder

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.