Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Traverse a matrix along anti-diagonals, alternating direction (up-right first).
Problem: Traverse a matrix along anti-diagonals, alternating direction (up-right first).
def diag(m):
R, C = len(m), len(m[0]); out = []
for s in range(R + C - 1):
cells = [m[r][s - r] for r in range(max(0, s - C + 1), min(R, s + 1))]
out += cells[::-1] if s % 2 == 0 else cells
return out
print(diag([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))What is printed?- A. [1, 2, 4, 3, 5, 7, 6, 8, 9]
- B. [1, 4, 2, 3, 5, 7, 8, 6, 9]
- C. [1, 2, 4, 7, 5, 3, 6, 8, 9]
- D. [1, 2, 4, 7, 5, 3, 8, 6, 9]
Correct answer: C. [1, 2, 4, 7, 5, 3, 6, 8, 9]
Diagonals by r + c: [1], [2, 4], [3, 5, 7], [6, 8], [9]. Even diagonals go up (reversed: 7, 5, 3), odd ones go down (2, 4 and 6, 8): 1, 2, 4, 7, 5, 3, 6, 8, 9.
More Coding Interview Problems questions
- Edge case: building a 3 × 3 grid with list multiplication. python grid = [[0] 3] 3 grid[0][0] = 1 print(grid) What is printed?
- 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…