ProgrammingVery hardTCS NQT · Accenture

Array a = [3, 4, 1, 2, 4, 2, 1, 3] and target K = 7. The procedure below counts contiguous subarrays whose sum is exactly K, using prefix sums and a count of earlier prefixes. What is printed?

Array a = [3, 4, 1, 2, 4, 2, 1, 3] and target K = 7. The procedure below counts contiguous subarrays whose sum is exactly K, using prefix sums and a count of earlier prefixes. What is printed?
P = 0; count = 0; seen[0] = 1
for each element x in a
    P = P + x
    count = count + seen[P - K]
    seen[P] = seen[P] + 1
end for
Print count
  1. A. 19
  2. B. 4
  3. C. 1
  4. D. 2

Correct answer: B. 4

The prefix sums are 3, 7, 8, 10, 14, 16, 17, 20, and counting earlier prefixes that differ from the current one by exactly 7 gives 4 subarrays. Counting subarrays with sum at most 7 gives 19, counting adjacent pairs that sum to 7 gives 1, and counting subarrays that sum to 14 gives 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic