ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from collections import Counter
a = [1, -1, 2, -2, 0]
cnt = Counter({0: 1})
s = 0
ans = 0
for x in a:
    s += x
    ans += cnt[s]
    cnt[s] += 1
print(ans)
  1. A. 4
  2. B. 5
  3. C. 3
  4. D. 6

Correct answer: D. 6

Prefix sums are 1, 0, 2, 0, 0 after the start 0. Any two equal prefix sums mark a subarray with sum 0. The value 0 occurs four times in total including the start, which gives C(4, 2) = 6 pairs, and the value 1 and 2 give none.

More Python Programming questions

Exams that ask this topic