Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Count subarrays whose sum lies in [lo, hi] using prefix sums and a sorted list (bisect).

Problem: Count subarrays whose sum lies in [lo, hi] using prefix sums and a sorted list (bisect).
from bisect import bisect_left, bisect_right, insort
def count(a, lo, hi):
    pre, s, res = [0], 0, 0
    for x in a:
        s += x
        res += bisect_right(pre, s - lo) - bisect_left(pre, s - hi)
        insort(pre, s)
    return res
print(count([-2, 5, -1, 3, -4, 2], -2, 2))
What is printed?
  1. A. 11
  2. B. 6
  3. C. 13
  4. D. 8

Correct answer: A. 11

A subarray ending here has sum s − p for an earlier prefix p, so we need s − hi ≤ p ≤ s − lo, counted by two binary searches. The total 11 matches checking all 21 subarrays (an O(n log n) merge-sort or BIT version scales to 10⁵).

More Coding Interview Problems questions

Exams that ask this topic