ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

What is printed?
def count_k(a, k):
    pre = {0: 1}
    s = 0
    ans = 0
    for x in a:
        s += x
        ans += pre.get(s - k, 0)
        pre[s] = pre.get(s, 0) + 1
    return ans
print(count_k([1, -1, 0, 1, -1], 0))
  1. A. 7
  2. B. 6
  3. C. 5
  4. D. 4

Correct answer: A. 7

The prefix sums are 0,1,0,0,1,0. Equal prefix values give zero-sum subarrays: four zeros give 6 pairs and two ones give 1 pair, a total of 7.

More Python Programming questions

Exams that ask this topic