Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Each cell of a grid holds 0 (empty) or 1. Return a grid of the distance from each cell to its nearest 0.
Problem: Each cell of a grid holds 0 (empty) or 1. Return a grid of the distance from each cell to its nearest 0.
from collections import deque
def near0(g):
R, C = len(g), len(g[0])
d = [[-1] * C for _ in range(R)]; q = deque()
for r in range(R):
for c in range(C):
if g[r][c] == 0: d[r][c] = 0; q.append((r, c))
while 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 d[nr][nc] == -1:
d[nr][nc] = d[r][c] + 1; q.append((nr, nc))
return d
print(near0([[1, 1, 1], [1, 1, 1], [1, 1, 0]])[0])What is the first row printed?- A. [2, 2, 2]
- B. [4, 3, 3]
- C. [4, 3, 2]
- D. [3, 2, 1]
Correct answer: C. [4, 3, 2]
Multi-source BFS from every 0 at once gives each cell its Manhattan-style grid distance to the nearest 0 in O(R·C). The only 0 is at (2,2): row 0 is at distances 4, 3, 2. Running a separate BFS from every 1 would be O((R·C)²).
More Coding Interview Problems questions
- Problem: A city grid has V = 10⁵ junctions; every road takes either 0 minutes (flyover) or 1 minute. What is the most efficient way to get…
- Problem: A graph of flights has prices; find the cheapest price from src to dst using at most k stops (Bellman–Ford limited to k + 1…
- Problem: Count connected components of an undirected graph given as an edge list on n nodes. cpp int find(vector<int>& p, int x) { return…
- Problem: Return the k-th largest value in a stream of scores using a min-heap of size k. python import heapq def kthlargest(a, k): h = []…
- Problem: From n = 10⁶ log entries, return the k = 10 most frequent error codes. Which approach is the most efficient?
- Problem: Merge k sorted lists of order timestamps into one sorted list. python import heapq def mergek(lists): h = [(l[0], i, 0) for i, l…