Data Structures & AlgorithmsModerateTCS NQT · prefix sums

Problem: How many contiguous subarrays of [1, 2, 3, 4, 5] have sum exactly 5? Run the code.

Problem: How many contiguous subarrays of [1, 2, 3, 4, 5] have sum exactly 5? Run the code.
a = [1, 2, 3, 4, 5]
print(sum(1 for i in range(len(a)) for j in range(i, len(a)) if sum(a[i:j + 1]) == 5))
What is printed?
  1. A. 2
  2. B. 1
  3. C. 3
  4. D. 4

Correct answer: A. 2

The qualifying subarrays are [2, 3] and [5], so the answer is 2. The subarray [1, 2, 3] sums to 6, which is not 5, and the prefix-sum hash count gives the same result.

More Coding Interview Problems questions

Exams that ask this topic