Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: In a grid, 0 is open and 1 is a wall. Find the shortest path length (in cells) from the top-left to the bottom-right moving in 8 directions, or −1.
Problem: In a grid, 0 is open and 1 is a wall. Find the shortest path length (in cells) from the top-left to the bottom-right moving in 8 directions, or −1.
from collections import deque
def sp(g):
n = len(g)
if g[0][0] or g[n-1][n-1]: return -1
q, seen = deque([(0, 0, 1)]), {(0, 0)}
while q:
r, c, d = q.popleft()
if (r, c) == (n - 1, n - 1): return d
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and not g[nr][nc] and (nr, nc) not in seen:
seen.add((nr, nc)); q.append((nr, nc, d + 1))
return -1
print(sp([[0, 0, 0], [1, 1, 0], [1, 1, 0]]), sp([[0, 1], [1, 0]]), sp([[1, 0], [0, 0]]))What is printed?- A. 4 2 -1
- B. 5 2 -1
- C. 4 -1 -1
- D. 3 2 -1
Correct answer: A. 4 2 -1
BFS counts cells: (0,0) → (0,1) → (1,2) → (2,2) is 4 cells using one diagonal. In the 2 × 2 grid the diagonal move gives 2. A blocked start returns −1 immediately. Marking cells on enqueue keeps it O(n²).
More Coding Interview Problems questions
- Problem: Each cell of a grid holds 0 (empty) or 1. Return a grid of the distance from each cell to its nearest 0. python from collections…
- 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?