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?
- A. [[0, 5, 0], [0, 0, 0]] [[0, 5, 0], [0, 0, 0]]
- B. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 0, 0]]
- C. [[5, 5, 5], [0, 0, 0]] [[0, 5, 0], [0, 0, 0]]
- 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
- Problem: Count the contiguous subarrays with an ODD sum using prefix-sum parity counts. python def oddsumsubarrays(a): even, odd, run, res…
- Problem: Find the length of the LONGEST contiguous subarray whose sum equals k; values can be negative, so a sliding window is not valid…
- Problem: Count contiguous subarrays of positive integers whose product is strictly less than k, using a shrinking window. python def…
- Problem: An array is a permutation of 0..n−1. Split it into the maximum number of chunks so that sorting each chunk separately and…
- Problem: Seat numbers must become pairwise distinct; one move increments a seat number by 1. Find the minimum moves (sort, then push each…
- Problem: Two engineers list their free slots as sorted, internally disjoint closed intervals. Return every common free interval. python…