Data Structures & AlgorithmsVery hardProduct company OA · Amazon/Microsoft-style OA

Array a = [5, -3, 2, 4, -6, 1, 3, -2]. How many non-empty contiguous subarrays have a sum in the closed range [0, 4]?

  1. A. 20
  2. B. 18
  3. C. 22
  4. D. 17

Correct answer: A. 20

Prefix sums turn the question into counting pairs p[i] < p[j] with p[j] - 4 <= p[i] <= p[j] - 0. Keeping the prefixes in a sorted structure answers each query in logarithmic time, and the count of pairs is the answer.

More Coding Interview Problems questions

Exams that ask this topic