Data Structures & AlgorithmsHardGATE CS · DSA

A 2-D prefix-sum table answers rectangle queries in O(1). For the 4 × 4 matrix (rows separated by ';', 0-based) 1 3 7 6; 6 8 8 6; 1 9 7 8; 2 1 3 3, what is the sum of the sub-rectangle from (1, 1) to (2, 3) inclusive?

  1. A. 38
  2. B. 45
  3. C. 70
  4. D. 46

Correct answer: D. 46

Sum = P[3][4] − P[1][4] − P[3][1] + P[1][1] = 46, where P is 1-based. Forgetting to add back the doubly-subtracted corner gives 45.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic