Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Every minute, fresh oranges (1) next to rotten ones (2) rot (4 directions). How many minutes until no fresh orange remains (−1 if impossible)?
Problem: Every minute, fresh oranges (1) next to rotten ones (2) rot (4 directions). How many minutes until no fresh orange remains (−1 if impossible)?
from collections import deque
def rot(g):
R, C = len(g), len(g[0]); q = deque(); fresh = 0
for r in range(R):
for c in range(C):
if g[r][c] == 2: q.append((r, c, 0))
elif g[r][c] == 1: fresh += 1
t = 0
while q:
r, c, t = q.popleft()
for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if 0 <= x < R and 0 <= y < C and g[x][y] == 1:
g[x][y] = 2; fresh -= 1; q.append((x, y, t + 1))
return t if fresh == 0 else -1
print(rot([[2,1,0,2],[1,0,1,1],[1,1,0,1]]))What is printed?- A. 4
- B. 2
- C. -1
- D. 3
Correct answer: D. 3
Multi-source BFS from both rotten oranges: minute 1 rots (0,1), (1,0), (1,3); minute 2 rots (2,0), (1,2), (2,3); minute 3 rots (2,1). All 7 fresh oranges are reached, so the answer is 3.
More Coding Interview Problems questions
- Problem: Find the path from node 0 to node 3 with the maximum product of edge success probabilities (Dijkstra on −log p, or a max-heap on…
- Problem: Each bus route is a loop of stops. Find the fewest buses needed to travel from stop S to stop T (BFS over routes, not stops)…
- Problem: Hire exactly K workers; each is paid in proportion to quality, and at least their minimum wage. Minimise total pay (sort by…
- Problem: In a sorted array every value appears twice except one. Find it in O(log n) using index parity. python def single(a): lo, hi = 0…
- Problem: Split an array into contiguous parts of length at most k; every element of a part becomes that part's maximum. Maximise the final…
- Problem: Build a binary tree whose leaves (in order) are the array values; each internal node's value is (max leaf on its left) × (max…