Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

What is printed? (prefix sums for range queries)

What is printed? (prefix sums for range queries)
a = [3, -2, 5, 1, -4, 6]
P = [0]
for x in a: P.append(P[-1] + x)
q = [(0, 2), (1, 4), (3, 5), (5, 5)]
print([P[r + 1] - P[l] for l, r in q])
  1. A. [6, 0, 3, 0]
  2. B. [1, 0, 3, 6]
  3. C. [6, 0, 3, 6]
  4. D. [6, -4, 3, 6]

Correct answer: C. [6, 0, 3, 6]

P = [0, 3, 1, 6, 7, 3, 9]. Sum a[l..r] = P[r + 1] − P[l]: (0,2) → 6, (1,4) → 3 − 3 = 0, (3,5) → 9 − 6 = 3, (5,5) → 9 − 3 = 6. Using P[r] − P[l] drops the last element. O(1) per query after O(n) setup.

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

Exams that ask this topic