Rotting Oranges solution explained
Rotting Oranges asks how many minutes pass until no fresh orange is left, when every rotten orange spoils its fresh neighbors above, below, left and right once per minute; if some fresh orange can never be reached, the answer is -1. Solve it with a multi-source breadth-first search: put every rotten orange in the queue at minute 0, spread one layer per minute, and count fresh oranges as they turn. It runs in O(rows × cols) time.
By Evin JohnPublished 9 min read
The setup
A crate is drawn as a grid. A cell is empty (0), holds a fresh orange (1) or holds a rotten one (2). Every minute, every rotten orange spoils each fresh orange directly next to it, horizontally or vertically. All of this happens at the same time, so an orange that turns rotten during minute 3 starts spreading only in minute 4. Return the number of minutes until no fresh orange remains, or -1 if at least one fresh orange can never be reached.
Crate A Crate B Crate C
2 1 0 1 2 1 1 2 1 0
1 1 0 1 0 0 0 0 0 1
0 1 1 1 1 1 2
answer: 7 answer: 2 answer: -1In crate A, the rot has to snake down the middle, across the bottom row and back up the right column, so the last orange, top right, turns in minute 7. In crate B two rotten oranges work in parallel, which is why the answer is 2 rather than 4. In crate C the orange at the bottom right has empty cells on every side that matters, so it stays fresh forever.
Clarify before coding: what if there are no fresh oranges at all (normally 0), what if there are fresh ones but no rotten ones (normally -1, unless there are none fresh), and may you change the grid in place?
Why it is a favorite
Most candidates have run breadth-first search from one starting cell. This problem checks whether you see that several starting cells can share one queue, and whether you can measure time as BFS depth. It also has two return-value traps, 0 and -1, that reveal whether you read the statement closely. It appears often enough in practice lists that interviewers expect a clean, quick solution and may use the leftover time for a variant.
Simulating minute by minute
The direct approach copies the story. Each minute, scan the whole grid, find fresh oranges next to a rotten one, and mark them to turn rotten at the end of the minute. Mark them in a separate list first, because turning them immediately would let rot travel several cells in one minute. Stop when a minute changes nothing, then check whether any fresh orange is left. It is correct, but every minute costs a full scan, and a long winding path like crate A can take on the order of rows × cols minutes, so the worst case is O((rows × cols)²).
def minutes_by_simulation(grid):
g = [row[:] for row in grid]
h, w = len(g), len(g[0]) if g else 0
minutes = 0
while True:
turning = [(r, c) for r in range(h) for c in range(w) if g[r][c] == 1 and any(
0 <= r + dr < h and 0 <= c + dc < w and g[r + dr][c + dc] == 2
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))]
if not turning:
break
for r, c in turning:
g[r][c] = 2
minutes += 1
return -1 if any(1 in row for row in g) else minutesMulti-source BFS
Breadth-first search already explores in rings of equal distance, so let it do the timing. Scan once: push every rotten orange into the queue and count the fresh ones. Then process the queue one layer at a time. Everything in the current layer rotted at the same minute; each fresh neighbor of a cell in that layer rots one minute later, so mark it rotten right away, decrease the fresh count and push it. Each time a layer produces at least one newly rotten orange, the clock moves forward by one. When the queue runs dry, return the clock if the fresh count is zero, otherwise -1.
from collections import deque
def oranges_rotting(grid):
g = [row[:] for row in grid]
h, w = len(g), len(g[0]) if g else 0
queue, fresh = deque(), 0
for r in range(h):
for c in range(w):
if g[r][c] == 2:
queue.append((r, c))
elif g[r][c] == 1:
fresh += 1
minutes = 0
while queue and fresh:
for _ in range(len(queue)): # one minute = one layer
r, c = queue.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < h and 0 <= nc < w and g[nr][nc] == 1:
g[nr][nc] = 2
fresh -= 1
queue.append((nr, nc))
minutes += 1
return minutes if fresh == 0 else -1The loop condition while queue and fresh is doing real work. Stopping as soon as nothing fresh remains avoids counting one extra empty minute after the last orange turns, which is the most common off-by-one in this problem. It also handles the zero case for free: with no fresh fruit, the loop never runs and the answer is 0.
function orangesRotting(grid) {
const h = grid.length;
const w = h ? grid[0].length : 0;
const g = grid.map((row) => row.slice());
const queue = []; // entries: [row, col, minute]
let fresh = 0;
for (let r = 0; r < h; r++) {
for (let c = 0; c < w; c++) {
if (g[r][c] === 2) queue.push([r, c, 0]);
else if (g[r][c] === 1) fresh++;
}
}
let last = 0;
const steps = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let head = 0; head < queue.length; head++) {
const [r, c, t] = queue[head];
for (const [dr, dc] of steps) {
const nr = r + dr, nc = c + dc;
if (nr < 0 || nr >= h || nc < 0 || nc >= w || g[nr][nc] !== 1) continue;
g[nr][nc] = 2;
fresh--;
last = t + 1;
queue.push([nr, nc, t + 1]);
}
}
return fresh === 0 ? last : -1;
}Here the time travels with each cell, and the answer is the time of the last orange that turned. Because BFS hands out times in non-decreasing order, the last assignment is also the largest. This version sidesteps the extra-minute problem entirely, and some people find it easier to explain. The queue never shrinks, so a head index replaces shift().
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Minute-by-minute full scans | O((R·C)²) worst case | O(R·C) for the copy and the list of turning cells |
| Separate BFS from each rotten orange, keep the minimum time per cell | O(k · R·C) for k rotten oranges | O(R·C) |
| One multi-source BFS | O(R·C) | O(R·C) for the copy and queue |
Variants with the same skeleton
- Distance to the nearest zero for every cell of a 0/1 matrix: start the queue with every zero.
- Rooms and gates: fill each empty room with its distance to the closest gate, with walls blocking movement.
- Shortest escape for a person when fire spreads too: run the fire BFS first to get the time each cell burns, then run the person's BFS and only step into cells before the fire arrives.
- Rot spreads diagonally as well: switch to eight directions.
- Report the minute each orange rotted: write the minute into a separate grid as you push.
Edge cases
- No fresh oranges at all: 0.
- Fresh oranges but no rotten ones: -1.
- A fresh orange walled in by empty cells: -1, even if every other orange rots.
- Several rotten oranges spreading toward the same region, which should take the shorter time.
- A single row or a single cell.
Common errors
- Starting a separate search from each rotten orange and adding times instead of taking the earliest.
- Counting a final minute in which nothing changed, so the answer is one too high.
- Turning neighbors rotten during a scan in the simulation, so rot jumps several cells in one minute.
- Returning -1 when the grid has no oranges at all.
- Forgetting the fresh counter and rescanning the whole grid at the end; correct, but worth noting you could avoid it.
A walkthrough you could give
Fictional example
- Candidate
- Rot spreads one step per minute in every direction, which is exactly how breadth-first search expands, so the minute an orange rots is its BFS distance from the nearest rotten orange.
- Candidate
- Since all the rotten ones start together, I will put all of them in the queue at time zero. One search then gives every orange its earliest time.
- Candidate
- I count fresh oranges first and decrement as they turn. If the queue empties with fresh ones left, they were unreachable, so I return minus one.
- Interviewer
- Why not run a BFS from each rotten orange?
- Candidate
- That works if I keep the minimum per cell, but it repeats the work once per source. A shared queue does it in one linear pass.
Related problems
Two of the grid problems here also start from many cells at once: Pacific Atlantic Water Flow seeds a search from each coast, and Surrounded Regions seeds one from the whole border. For breadth-first search on an explicit graph, see Clone Graph. For a contrast in pattern, Letter Combinations of a Phone Number is backtracking rather than search.
How Natively can help you prepare
Off-by-one minutes are easy to miss when you only read solutions. Practicing aloud helps more. Natively, on Mac or Windows, can read the crate grid from a screenshot during a mock session, suggest the multi-source search and the fresh counter, and transcribe your walkthrough so you can check whether you covered the 0 and -1 cases. More on the interview assistant.
Questions people ask
How do you solve Rotting Oranges?
Put every rotten orange in one queue and count the fresh ones. Run breadth-first search layer by layer, rotting fresh neighbors and lowering the count; each layer is one minute. Return the minutes if no fresh orange is left, otherwise -1.
Why use multi-source BFS for Rotting Oranges?
All rotten oranges spread at the same time, and an orange rots at the minute equal to its distance from the nearest rotten one. Starting BFS from all of them together finds every earliest time in a single O(rows × cols) pass.
What does Rotting Oranges return when there are no fresh oranges?
0, because nothing needs to rot, even if the grid has no rotten oranges either. Fresh oranges with no way for rot to reach them give -1.
Why is my answer one minute too high?
The loop probably counts a final layer in which nothing new rotted. Stop when no fresh oranges remain, or store each orange's rot time in the queue and return the last time assigned.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
