Data Structures & AlgorithmsVery hardProduct Company SDE · prefix-sum OA

Problem: How many subarrays of [3, 4, 7, 2, -3, 1, 4, 2] have sum exactly 7? Run the prefix-sum hash code.

Problem: How many subarrays of [3, 4, 7, 2, -3, 1, 4, 2] have sum exactly 7? Run the prefix-sum hash code.
from collections import Counter
a = [3, 4, 7, 2, -3, 1, 4, 2]
c = Counter({0: 1})
s = ans = 0
for x in a:
    s += x
    ans += c[s - 7]
    c[s] += 1
print(ans)
What is printed?
  1. A. 3
  2. B. 5
  3. C. 6
  4. D. 4

Correct answer: D. 4

Prefix sums stored in a hash map count every earlier prefix equal to s - 7, so each subarray with sum 7 is counted once; the total is 4.

More Coding Interview Problems questions

Exams that ask this topic