Skip to content
mlmentorship

Rotting Oranges

Seed all simultaneous sources before FIFO spreading, mark fresh cells on enqueue, and distinguish scheduled arrival, input mutation and unreachable fresh cells.

Published · 15 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Rotting Oranges

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A rectangular mutable integer grid: 0 means empty, 1 fresh, and 2 rotten. Output. Return the first minute when every fresh orange has rotted, or -1 if some fresh orange is unreachable. Rules. All initially rotten oranges begin spreading at time zero. Each minute they infect fresh orthogonal neighbors simultaneously; empty cells block spread. The reference changes reached fresh cells to 2 and leaves unreachable fresh cells unchanged. No fresh oranges, including an empty grid, means zero minutes. Example. [[2, 1, 1], [1, 1, 0], [0, 1, 1]] returns 4. For [[2, 0, 1]], return -1 because the empty middle cell separates the fresh orange.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Seed every rotten cell at time zero. FIFO processes nearest-source arrivals. Mark each fresh cell before enqueueing it.

Problem trace

A newly scheduled cell spreads only when its own minute arrives

Worked example: each frozen queue layer advances time by one minuteThis example reaches its last fresh orange at minute 4. Cells in the same wave share a time; six infections do not imply six minutes.Equal arrival times form onesimultaneous infection wave01212wallwall34Minute buckets: zero contains onlythe initial seedt00,0t10,11,0t20,21,1t32,1t42,2Six new infections fit into fourwaves. The last cell arrives atminute four.
Read it this way: This example reaches its last fresh orange at minute 4. Cells in the same wave share a time; six infections do not imply six minutes. Do the two cells arriving at minute one require two successive minutes?
Full interview answer 15 min read

Determine how many minutes it takes for rotting to spread from all initially rotten oranges to every fresh orange.

Problem

Input. A rectangular mutable integer grid: 0 means empty, 1 fresh, and 2 rotten.

Output. Return the first minute when every fresh orange has rotted, or -1 if some fresh orange is unreachable.

Rules. All initially rotten oranges begin spreading at time zero. Each minute they infect fresh orthogonal neighbors simultaneously; empty cells block spread. The reference changes reached fresh cells to 2 and leaves unreachable fresh cells unchanged. No fresh oranges, including an empty grid, means zero minutes.

Example. [[2, 1, 1], [1, 1, 0], [0, 1, 1]] returns 4. For [[2, 0, 1]], return -1 because the empty middle cell separates the fresh orange.

Picture

Seed all initial 2 cells as (row, col, 0) before the first pop. Reuse the equal-cost frontier rule: FIFO processes nondecreasing timestamps, so first discovery gives minimum distance from any source.

For [[2,1,1],[1,1,0],[0,1,1]]:

After processingQueuefresh
Seed sources[(0,0,0)]6
Time 0[(1,0,1),(0,1,1)]4
Time 1[(1,1,2),(0,2,2)]2
Time 2[(2,1,3)]1
Time 3[(2,2,4)]0
Time 4[]0

At time one, both parents can reach (1,1). The first marks it before enqueueing; the second sees 2 and skips it. With simultaneous sources [[2,1,2]], the center is likewise scheduled once at time one, not twice.

A newly marked 2 means infection is scheduled at the queued timestamp, not the current popped time. The final cell is queued for time four while minutes is still three. Its later pop makes the returned answer four.

[[1]] has fresh cells but no source, so returns -1. Empty grids and [[0]] return zero.

Different move costs or delayed source activation need a different priority and initial-distance contract, not this FIFO rule unchanged.

Problem trace

A newly scheduled cell spreads only when its own minute arrives

Input and goalFind how many minutes all reachable fresh oranges need to rot.
Seed every time-zero sourceEnqueue source (0,0,0) and count six fresh cells. Values are 2 for rotten, 1 for fresh and 0 for empty.
2t=011110011
queueState[(0,0,0)]fresh6minute0
t
(0, 0)
queue state
[(0,0,0)]
fresh
6

Recognize it
Use multi-source BFS for simultaneous unweighted spreading, infection, nearest-source distance, or minimum elapsed steps when every source acts at time zero and each move has equal cost.
Keep true
When (row,col,time) is popped, time is its minimum distance from any initial rotten cell. Marking a fresh neighbor rotten before enqueueing ensures that cell is queued once at time + 1.
Reuse it
Seed all equal-priority sources before BFS, mark neighbors when enqueued, and carry distance in the queue; the same mechanism solves nearest gate, fire spread, and shortest distance to any facility.
Enqueue source (0,0,0) and count six fresh cells. Values are 2 for rotten, 1 for fresh and 0 for empty. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can an orange scheduled for time four not spread at time three?
Reference drawing

Problem trace

A newly scheduled cell spreads only when its own minute arrives

Worked example: each frozen queue layer advances time by one minuteThis example reaches its last fresh orange at minute 4. Cells in the same wave share a time; six infections do not imply six minutes.Equal arrival times form onesimultaneous infection wave01212wallwall34Minute buckets: zero contains onlythe initial seedt00,0t10,11,0t20,21,1t32,1t42,2Six new infections fit into fourwaves. The last cell arrives atminute four.
Execution trace
Input and goalFind how many minutes all reachable fresh oranges need to rot.
Seed every time-zero sourceEnqueue source (0,0,0) and count six fresh cells. Values are 2 for rotten, 1 for fresh and 0 for empty.
2t=011110011
queueState[(0,0,0)]fresh6minute0
t
(0, 0)
queue state
[(0,0,0)]
fresh
6

Recognize it
Use multi-source BFS for simultaneous unweighted spreading, infection, nearest-source distance, or minimum elapsed steps when every source acts at time zero and each move has equal cost.
Keep true
When (row,col,time) is popped, time is its minimum distance from any initial rotten cell. Marking a fresh neighbor rotten before enqueueing ensures that cell is queued once at time + 1.
Reuse it
Seed all equal-priority sources before BFS, mark neighbors when enqueued, and carry distance in the queue; the same mechanism solves nearest gate, fire spread, and shortest distance to any facility.
Enqueue source (0,0,0) and count six fresh cells. Values are 2 for rotten, 1 for fresh and 0 for empty. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can an orange scheduled for time four not spread at time three?
Read it this way: This example reaches its last fresh orange at minute 4. Cells in the same wave share a time; six infections do not imply six minutes. Do the two cells arriving at minute one require two successive minutes?

Code

from collections import deque

def rotting_oranges(grid: list[list[int]]) -> int:
   if not grid or not grid[0]:
      return 0

   queue = deque(
      (row, col, 0)
      for row in range(len(grid))
      for col in range(len(grid[0]))
      if grid[row][col] == 2
   )
   fresh = sum(cell == 1 for row in grid for cell in row)

   minutes = 0
   while queue:
      row, col, minutes = queue.popleft()
      for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
         new_row = row + row_step
         new_col = col + col_step
         if 0 <= new_row < len(grid) and 0 <= new_col < len(grid[0]):
            if grid[new_row][new_col] == 1:
               grid[new_row][new_col] = 2
               fresh -= 1
               queue.append((new_row, new_col, minutes + 1))

   return minutes if fresh == 0 else -1

Cost: time and space.

Change Ownership or Adjacency

Start from rotting_oranges. Source timing and equal edge costs stay fixed in both adaptations.

  1. Preserve the caller’s grid.

    New task: Return the same arrival time without modifying input.

    Picture and change: Copy every row before the source function uses 2 as its discovery mark. Copying only the outer list still shares rows and therefore still changes the caller’s cells.

    Code: Uses rotting_oranges above:

    def rotting_time_preserving(grid):
       return rotting_oranges([row[:] for row in grid])

    Check: The six-fresh-cell example returns four and retains the original grid, including every 1.

    Use when: Mutation permission changes. The row copies add storage; work remains linear in the grid size.

  2. Permit diagonal spreading.

    New task: All eight neighboring cells connect by one-minute edges.

    Picture and change: Change only adjacency. Keep all-source seeding, FIFO timestamps, the fresh counter and marking before enqueueing.

    Code: Complete replacement, still mutating reachable fresh cells:

    from collections import deque
    
    
    def rotting_eight_neighbors(grid):
       if not grid or not grid[0]:
          return 0
       queue = deque(
          (row, col, 0)
          for row in range(len(grid))
          for col in range(len(grid[0]))
          if grid[row][col] == 2
       )
       fresh = sum(cell == 1 for row in grid for cell in row)
       directions = [
          (row_step, col_step)
          for row_step in (-1, 0, 1)
          for col_step in (-1, 0, 1)
          if row_step or col_step
       ]
       minute = 0
       while queue:
          row, col, minute = queue.popleft()
          for row_step, col_step in directions:
             new_row, new_col = row + row_step, col + col_step
             if 0 <= new_row < len(grid) and 0 <= new_col < len(grid[0]):
                if grid[new_row][new_col] == 1:
                   grid[new_row][new_col] = 2
                   fresh -= 1
                   queue.append((new_row, new_col, minute + 1))
       return minute if fresh == 0 else -1

    Check: [[2,0,1],[0,1,0]] reaches the center at minute one, then the top-right cell at minute two. The orthogonal source leaves both fresh cells unreachable and returns -1.

    Use when: The edge relation changes but costs remain equal. At most eight neighbors per cell preserves time and space.

Rebuild Arrival Times

Why can DFS depth give the wrong minute?

Answer: DFS may follow a long route before a shorter one. FIFO processes all smaller unit-cost distances first.