Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count subarrays whose sum is exactly k when values may be negative (prefix sums + hash map of prefix counts).

Problem: Count subarrays whose sum is exactly k when values may be negative (prefix sums + hash map of prefix counts).
def count(a, k):
    seen, s, res = {0: 1}, 0, 0
    for x in a:
        s += x
        res += seen.get(s - k, 0)
        seen[s] = seen.get(s, 0) + 1
    return res
print(count([3, 4, -7, 1, 3, 3, 1, -4], 7))
What is printed?
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 2

Correct answer: B. 4

Prefix sums are 0, 3, 7, 0, 1, 4, 7, 8, 4. For each prefix P, add how many earlier prefixes equal P − 7: the first 7 matches one 0, the second 7 matches two 0s, and 8 matches the 1, for a total of 4. A two-pointer window fails here because negatives break monotonicity.

More Coding Interview Problems questions

Exams that ask this topic