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?
  1. A. 6 6 6 4
  2. B. 6 6 4 4
  3. C. 2 6 3 4
  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

Exams that ask this topic