Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count the number of contiguous subarrays whose sum equals k. Values can be negative.

Problem: Count the number of contiguous subarrays whose sum equals k. Values can be negative.
def count_k(a, k):
    seen = {0: 1}
    p = ans = 0
    for x in a:
        p += x
        ans += seen.get(p - k, 0)
        seen[p] = seen.get(p, 0) + 1
    return ans
print(count_k([1, -1, 1, -1, 1], 1))
What is printed?
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 6

Correct answer: D. 6

Prefix sums are 1, 0, 1, 0, 1 (starting from 0). Each time p − 1 has been seen c times, c subarrays end here: 1 + 0 + 2 + 0 + 3 = 6. Without the initial {0: 1}, subarrays starting at index 0 are missed (answer 3). A sliding window fails because of the negatives. O(n).

More Coding Interview Problems questions

Exams that ask this topic