Data Structures & AlgorithmsVery hardProduct company OA
Problem: Each grid cell has an arrow; moving along a cell's arrow is free, moving in any other direction costs 1 (you change the arrow). Find the minimum cost from the top-left to the bottom-right cell with 0-1 BFS. What is printed (cost, number of cells reachable for free, largest finite distance)?
Problem: Each grid cell has an arrow; moving along a cell's arrow is free, moving in any other direction costs 1 (you change the arrow). Find the minimum cost from the top-left to the bottom-right cell with 0-1 BFS. What is printed (cost, number of cells reachable for free, largest finite distance)?
from collections import deque
g = ["RRD",
"DLL",
"RRU",
"LRD"]
R, C = len(g), len(g[0])
dirs = {"R": (0, 1), "L": (0, -1), "D": (1, 0), "U": (-1, 0)}
dist = [[10**9] * C for _ in range(R)]; dist[0][0] = 0
dq = deque([(0, 0)])
while dq:
r, c = dq.popleft()
for ch, (dr, dc) in dirs.items():
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C:
w = 0 if g[r][c] == ch else 1
if dist[r][c] + w < dist[nr][nc]:
dist[nr][nc] = dist[r][c] + w
(dq.appendleft if w == 0 else dq.append)((nr, nc))
print(dist[R - 1][C - 1], sum(row.count(0) for row in dist), max(max(r) for r in dist))What is printed?- A. 2 9 2
- B. 1 9 1
- C. 0 12 0
- D. 1 6 1
Correct answer: B. 1 9 1
Following the arrows from (0, 0) visits R, R, D, L, L, D, R, R and then U back into a loop, so the bottom row is never reached for free – 9 cells have cost 0. Changing one arrow (e.g. the U at (2, 2) to D) reaches the goal, so the answer is 1, and every cell of the last row is reachable with exactly one change. Weight-0 edges go to the deque front, weight-1 to the back: O(R·C).
More Coding Interview Problems questions
- Problem: Courses with prerequisites; at most k = 2 courses per semester. Exact DP over bitmasks of finished courses versus 'take the k…
- Problem: Count 'heavy pairs' i < j with a[i] > 2·a[j] in O(n log n) using a Fenwick tree over coordinate-compressed values (both x and 2x…
- Problem: A segment tree stores (sum, best prefix, best suffix, best subarray) per node to answer 'maximum subarray sum inside a[l..r]'…
- Problem: Smallest period of a log pattern from its KMP prefix function: per = n − π[n − 1], and s is a whole repetition only if per…
- Problem: Find the longest string that is a prefix of s, a suffix of s, and also occurs somewhere strictly inside (not as the prefix or the…
- Problem: Count pairs i < j with a[i] XOR a[j] < 6 using a binary trie that stores subtree counts (4-bit values). python def countless(a…