Data Structures & AlgorithmsHardCodeforces Div2 C · prefix sums
Problem: Using 2D prefix sums on M = [[1,2,3],[4,5,6],[7,8,9]], what is the sum of the rectangle with rows 1..2 and columns 1..2 (0-indexed, inclusive)?
Problem: Using 2D prefix sums on M = [[1,2,3],[4,5,6],[7,8,9]], what is the sum of the rectangle with rows 1..2 and columns 1..2 (0-indexed, inclusive)?
M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n, m = 3, 3
P = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n):
for j in range(m):
P[i + 1][j + 1] = M[i][j] + P[i][j + 1] + P[i + 1][j] - P[i][j]
r1, c1, r2, c2 = 1, 1, 2, 2
print(P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1])What is printed?- A. 24
- B. 30
- C. 22
- D. 28
Correct answer: D. 28
The rectangle is 5 + 6 + 8 + 9 = 28. The inclusion-exclusion step subtracts the two strips and adds back the corner counted twice.
More Coding Interview Problems questions
- Problem: How many pairs (i < j) of a = [1, 2, 3, 4, 5, 6, 7] have a[i] + a[j] divisible by 4? python a = [1, 2, 3, 4, 5, 6, 7] print(sum(1…
- Problem: Count the subarrays of a = [10, 5, 2, 6] whose product is strictly less than k = 100. python def cnt(a, k): if k <= 1: return 0 p…
- Problem: How many distinct subsequences (including the empty one) does 'aba' have? Run the DP below. python def dsub(s): dp = [1] last =…
- Problem: The minimum number of insertions to make 'abcab' a palindrome equals n minus the length of its longest palindromic subsequence…
- Problem: Count pairs (i < j) of a = [1, 2, 3] with a[i] XOR a[j] summed over all pairs. What is the total of the XOR values? Run the code…
- Problem: What is the maximum sum of a path from the top-left to the bottom-right of the grid [[1,3,1],[1,5,1],[4,2,1]] moving only right…