Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Edge case: building a 3 × 3 grid with list multiplication.
Edge case: building a 3 × 3 grid with list multiplication.
grid = [[0] * 3] * 3 grid[0][0] = 1 print(grid)What is printed?
- A. [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
- B. [[1, 1, 1], [0, 0, 0], [0, 0, 0]]
- C. It raises a TypeError
- D. [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
Correct answer: D. [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[0] * 3] * 3 repeats a reference to the SAME inner list three times, so changing grid[0][0] changes every row. Build rows independently with [[0] * 3 for _ in range(3)].
More Coding Interview Problems questions
- Edge case: lambdas created in a loop (closures). python fs = [lambda: i 10 for i in range(3)] gs = [lambda i=i: i 10 for i in range(3)]…
- Edge case: JavaScript event-loop ordering of synchronous code, a promise callback and a timer. javascript const out = []; out.push("A")…
- Problem: Split an array (duplicates allowed) into the most chunks such that sorting each chunk separately and concatenating gives the…
- Problem: Detect a 132 pattern (i < j < k with a[i] < a[k] < a[j]) in O(n) by scanning from the right with a stack. python def has132(a)…
- Problem: A single-threaded CPU log has entries 'id:start:t' and 'id:end:t' (an end at t covers time unit t). Functions can call each…
- Problem: Evaluate an expression with +, −, , / (integer division truncating toward zero) and no parentheses, using a stack. python def…