Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the length of the longest subarray of [1, 2, -3, 3, -1, -2] whose sum is zero? Run the prefix-sum code.

Problem: What is the length of the longest subarray of [1, 2, -3, 3, -1, -2] whose sum is zero? Run the prefix-sum code.
a = [1, 2, -3, 3, -1, -2]
first = {0: -1}
s = 0
best = 0
for i, x in enumerate(a):
    s += x
    if s in first:
        best = max(best, i - first[s])
    else:
        first[s] = i
print(best)
What is printed?
  1. A. 3
  2. B. 4
  3. C. 7
  4. D. 6

Correct answer: D. 6

The whole array sums to 0 (prefix 0 at index 5 matches the seed at −1), so the length is 6. Without the {0: −1} seed it is 3, 4 counts the zero-sum subarrays, and adding + 1 to i − first[s] gives 7.

More Coding Interview Problems questions

Exams that ask this topic