Data Structures & AlgorithmsVery hardProduct company OA
Problem: Count monotone paths (right/down) in a grid with blocked cells. The first version builds the table as [[0] C] R – every row is the SAME list object.
Problem: Count monotone paths (right/down) in a grid with blocked cells. The first version builds the table as [[0] * C] * R – every row is the SAME list object.
def paths(R, C, blocked):
dp = [[0] * C] * R
for r in range(R):
for c in range(C):
if (r, c) in blocked: dp[r][c] = 0
elif r == 0 and c == 0: dp[r][c] = 1
else: dp[r][c] = (dp[r - 1][c] if r else 0) + (dp[r][c - 1] if c else 0)
return dp[R - 1][C - 1]
def paths_ok(R, C, blocked):
dp = [[0] * C for _ in range(R)]
for r in range(R):
for c in range(C):
if (r, c) in blocked: continue
dp[r][c] = 1 if r == c == 0 else (dp[r - 1][c] if r else 0) + (dp[r][c - 1] if c else 0)
return dp[R - 1][C - 1]
print(paths(3, 3, set()), paths_ok(3, 3, set()), paths(3, 4, {(1, 1)}), paths_ok(3, 4, {(1, 1)}))What is printed?- A. 6 6 6 4
- B. 6 6 4 4
- C. 2 6 3 4
- D. 1 6 1 4
Correct answer: B. 6 6 4 4
Because all rows alias one list, dp[r − 1][c] reads the value written for column c during the previous row – the list behaves exactly like the classic rolling 1-D array dp[c] += dp[c − 1]. A blocked cell resets dp[c] to 0 in that shared row, which is again what the 1-D version does. So both functions print 6 for a 3 × 3 grid and 4 for the 3 × 4 grid with (1, 1) blocked. The aliasing bug only bites when an older row is read again later (e.g. dp[r − 2]) or when the whole table is inspected afterwards.
More Coding Interview Problems questions
- Problem: Two versions of Dijkstra. The second marks a vertex as finished the moment it is first PUSHED and never updates it again. python…
- Problem: KMP pattern search instrumented to count fallback steps k = π[k − 1] (total over the whole text). What is printed (matches…
- Problem: Single machine, jobs (name, duration, due time); lateness = finish − due. Minimise the MAXIMUM lateness. Compare…
- Problem: Two sorted price lists; list the 6 smallest sums a[i] + b[j] without generating all pairs (heap of frontier cells with a…
- Problem: Find all critical links (bridges) and critical routers (articulation points) with one DFS using discovery times and low-links…
- Problem: A drone must fly every route leg exactly once starting at P, choosing the alphabetically smallest destination whenever possible…