Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Answer sub-rectangle sum queries on a matrix in O(1) each with a 2-D prefix-sum table.
Problem: Answer sub-rectangle sum queries on a matrix in O(1) each with a 2-D prefix-sum table.
m = [[3, 0, 1, 4], [5, 6, 3, 2], [1, 2, 0, 1], [4, 1, 0, 5]]
R, C = len(m), len(m[0])
P = [[0] * (C + 1) for _ in range(R + 1)]
for r in range(R):
for c in range(C):
P[r+1][c+1] = m[r][c] + P[r][c+1] + P[r+1][c] - P[r][c]
def q(r1, c1, r2, c2):
return P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1][c1] + P[r1][c1]
print(q(1, 1, 2, 2), q(0, 0, 3, 3))What is printed?- A. 14 38
- B. 11 37
- C. 11 38
- D. 8 38
Correct answer: C. 11 38
The query adds the big prefix, subtracts the strips above and to the left, and adds back the doubly removed corner. Rows 1–2, columns 1–2 hold 6 + 3 + 2 + 0 = 11; the whole matrix sums to 38. Forgetting to add back P[r1][c1] is the classic bug.
More Coding Interview Problems questions
- Problem: A van with fixed capacity picks up and drops passengers; trip [n, from, to] carries n passengers from km 'from' to km 'to' (they…
- Problem: Start at index 0 and finish at the last index; from i you may jump to any of i+1..i+k. Maximise the sum of visited values…
- Problem: Move from the top-left to the bottom-right cell of a height grid (4 directions). The effort of a route is the largest absolute…
- Problem: n computers and a list of cables. You may unplug any cable and reconnect it elsewhere. Find the minimum number of moves to…
- Problem: A tree on nodes 1..n received one extra edge. Return the LAST edge in the input whose removal leaves a tree (union-find). python…
- Problem: Replace each word of a sentence by its shortest root from a dictionary (if any root is a prefix). python def replace(roots…