Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: A 3 × 4 grid of crop yields must answer 'total yield in rectangle (r1, c1)–(r2, c2)' in O(1) using a 2-D prefix table with one extra row and column.
Problem: A 3 × 4 grid of crop yields must answer 'total yield in rectangle (r1, c1)–(r2, c2)' in O(1) using a 2-D prefix table with one extra row and column.
g = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 1, 2, 3]]
R, C = len(g), len(g[0])
P = [[0] * (C + 1) for _ in range(R + 1)]
for i in range(R):
for j in range(C):
P[i+1][j+1] = g[i][j] + P[i][j+1] + P[i+1][j] - P[i][j]
def rect(r1, c1, r2, c2):
return P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1][c1] + P[r1][c1]
print(rect(1, 1, 2, 2), rect(0, 0, 2, 3), rect(0, 3, 2, 3))What is printed?- A. 16 51 15
- B. 15 51 15
- C. 16 51 12
- D. 16 50 15
Correct answer: A. 16 51 15
P[i][j] holds the sum of the top-left i × j block; a rectangle is P(bottom-right) minus the strip above minus the strip to the left plus the doubly-subtracted corner (inclusion–exclusion). Rows 1–2, cols 1–2: 6 + 7 + 1 + 2 = 16. The whole grid: 10 + 26 + 15 = 51. Column 3: 4 + 8 + 3 = 15. Build O(R·C), each query O(1).
More Coding Interview Problems questions
- Problem: Find the total of the sums of ALL contiguous subarrays without enumerating them: element a[i] lies in (i + 1)·(n − i) subarrays…
- Problem: A login service flags an account if the same device ID appears twice within at most k positions of the access log (|i − j| ≤ k)…
- Problem: A DP table for a 2 × 3 grid is created in two ways and one cell is set in each. python dp = [[0] 3] 2 dp[0][1] = 5 dp2 = [[0] 3…
- 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…