Data Structures & AlgorithmsHardProduct company OA · Amazon/Microsoft-style OA

What does this program print?

What does this program print?
a = [1, -1, 2, -2, 3]
seen = {0: 0}
s = 0; out = []
for i, x in enumerate(a, 1):
    s += x
    if s in seen:
        out.append((seen[s], i))
    else:
        seen[s] = i
print(out)
  1. A. [(0, 2), (2, 4)]
  2. B. [(0, 2), (0, 4)]
  3. C. [(0, 2), (1, 4)]
  4. D. [(0, 1), (2, 4)]

Correct answer: B. [(0, 2), (0, 4)]

The program records the first index of each prefix sum and reports a pair whenever a prefix repeats. The running sums after each element are 1, 0, 2, 0, 3, so the value 0 repeats at indices 2 and 4, each paired with the first occurrence at index 0.

More Coding Interview Problems questions

Exams that ask this topic