Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: A DP table for a 2 × 3 grid is created in two ways and one cell is set in each.

Problem: A DP table for a 2 × 3 grid is created in two ways and one cell is set in each.
dp = [[0] * 3] * 2
dp[0][1] = 5
dp2 = [[0] * 3 for _ in range(2)]
dp2[0][1] = 5
print(dp, dp2)
What is printed?
  1. A. [[0, 5, 0], [0, 0, 0]] [[0, 5, 0], [0, 0, 0]]
  2. B. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 0, 0]]
  3. C. [[5, 5, 5], [0, 0, 0]] [[0, 5, 0], [0, 0, 0]]
  4. D. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 5, 0]]

Correct answer: B. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 0, 0]]

[row] * 2 copies the REFERENCE to one inner list, so both rows are the same object and writing dp[0][1] also changes dp[1][1]. The comprehension builds a fresh list per row. This aliasing bug silently corrupts 2-D DP tables in Python; [0] * 3 itself is safe because integers are immutable.

More Coding Interview Problems questions

Exams that ask this topic