Data Structures & AlgorithmsModerateGATE CS · Product placement

A prefix-sum array P of A (P[0] = 0, P[i] = A[0] + … + A[i − 1]) is built. Which expression gives the sum A[l] + … + A[r] (0-based, inclusive)?

  1. A. P[r] − P[l]
  2. B. P[r + 1] − P[l + 1]
  3. C. P[r + 1] − P[l]
  4. D. P[r] − P[l − 1]

Correct answer: C. P[r + 1] − P[l]

P[r + 1] includes A[0..r] and P[l] includes A[0..l − 1]; their difference is exactly A[l..r]. P[r] − P[l − 1] is the formula for a 1-based prefix array.

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

Exams that ask this topic