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?- A. 4 -1 -1
- B. 4 -1 0
- C. 3 -1 0
- 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
- Problem: Courses with prerequisites [a, b] (b before a). Return one valid order using Kahn's algorithm with a min-heap for ties, or [] if…
- Problem: Detect a cycle in a directed dependency graph with three-colour DFS. python def hascycle(n, edges): adj = [[] for in range(n)]…
- Problem: Find the shortest travel time from node 0 to every node in a road network with non-negative weights. python import heapq def…
- Problem: A network has V = 10⁵ routers and E = 2 × 10⁵ links with latencies that can be negative (but no negative cycle). Which…
- Problem: Union-find with path compression answers which friends are in the same circle. How many circles remain after the unions? python…
- Problem: Find the minimum total cost to connect all offices (minimum spanning tree) using Kruskal's algorithm. python def kruskal(n…