Data Structures & AlgorithmsHardProduct Company SDE · prefix-sum OA
Problem: How many subarrays of [1, -1, 2, -2, 3, -3] have sum zero? Run the prefix-count code.
Problem: How many subarrays of [1, -1, 2, -2, 3, -3] have sum zero? Run the prefix-count code.
from collections import Counter
a = [1, -1, 2, -2, 3, -3]
c = Counter({0: 1})
s = 0
ans = 0
for x in a:
s += x
ans += c[s]
c[s] += 1
print(ans)What is printed?- A. 4
- B. 6
- C. 3
- D. 5
Correct answer: B. 6
Prefix sums are 0,1,0,2,0,3,0, and the value 0 appears four times, giving C(4,2) = 6 zero-sum subarrays. Counting only the adjacent cancelling pairs gives the trap 3.
More Coding Interview Problems questions
- Problem: A data stream needs the median of the last k elements. Which structure supports each slide in O(log k) time?
- Problem: Consider a connected undirected graph whose edge weights are all distinct. Which statement is true?
- Problem: What is the standard time complexity of bitmask DP for the travelling salesman problem on n cities?
- Array a = [3, -1, 2, 6, -4, 5, 1, -2]. How many non-empty contiguous subarrays have a sum divisible by 4?
- Binary array a = [1, 0, 1, 1, 0, 0, 1, 0, 1]. How many contiguous subarrays have exactly two 1s?
- Array a = [4, 2, 7, 1, 8, 3, 6, 5]. What is the largest sum of a contiguous subarray whose length is between 2 and 4 inclusive?