ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

What is printed?
g = [[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] = 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, 0, 2))
  1. A. 27 6
  2. B. 28 6
  3. C. 28 12
  4. D. 24 6

Correct answer: B. 28 6

The 2D prefix table answers a rectangle with four corner lookups. The bottom-right 2x2 block is 5+6+8+9 = 28, and the top row is 1+2+3 = 6.

More Python Programming questions

Exams that ask this topic