Rotting Oranges – Solution & Complexity

1. Understand the Goal

  • Identify the required output and the state that changes.
  • Use the examples to rule out tempting but incorrect interpretations.

2. Choose the Core Pattern

  • This problem is best exposed by Multi-source BFS expands one minute-layer at a time.
  • Maintain only the state needed for the next operation.

3. Build the Algorithm

  • Process each state once when possible.
  • Record state before scheduling dependent work to avoid duplicates.

4. Check Edge Cases

  • Verify the smallest input, impossible cases, and repeated values where allowed.
  • Keep output ordering deterministic.

5. Final Solution and Complexity

  • Time complexity is O(m*n).
  • Space complexity is O(m*n).
def oranges_rotting(grid: list[list[int]]) -> int:
    rows, cols = len(grid), len(grid[0]); queue = []; fresh = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 2: queue.append((r, c))
            elif grid[r][c] == 1: fresh += 1
    head = minutes = 0
    while head < len(queue) and fresh:
        end = len(queue)
        while head < end:
            r, c = queue[head]; head += 1
            for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
                    grid[nr][nc] = 2; fresh -= 1; queue.append((nr, nc))
        minutes += 1
    return minutes if fresh == 0 else -1

FAQ