Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: In a grid of fresh (1) and rotten (2) oranges, every minute rot spreads to 4-neighbours. Return the minutes until no fresh orange remains, or −1.

Problem: In a grid of fresh (1) and rotten (2) oranges, every minute rot spreads to 4-neighbours. Return the minutes until no fresh orange remains, or −1.
from collections import deque
def rot(g):
    R, C = len(g), len(g[0])
    q = deque((r, c) for r in range(R) for c in range(C) if g[r][c] == 2)
    fresh = sum(row.count(1) for row in g); t = 0
    while q and fresh:
        for _ in range(len(q)):
            r, c = q.popleft()
            for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
                if 0 <= nr < R and 0 <= nc < C and g[nr][nc] == 1:
                    g[nr][nc] = 2; fresh -= 1; q.append((nr, nc))
        t += 1
    return t if fresh == 0 else -1
print(rot([[2, 1, 1], [1, 1, 0], [0, 1, 1]]), rot([[2, 1, 1], [0, 1, 1], [1, 0, 1]]), rot([[0, 2]]))
What is printed?
  1. A. 4 -1 -1
  2. B. 4 -1 0
  3. C. 3 -1 0
  4. D. 4 4 0

Correct answer: B. 4 -1 0

Multi-source BFS: all rotten oranges start in the queue at time 0 and each round is one minute. The far corner (2,2) is reached at minute 4. In the second grid the orange at (2,0) is walled off, so −1. With no fresh oranges the answer is 0, not −1. O(R·C).

More Coding Interview Problems questions

Exams that ask this topic