ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

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

Correct answer: C. 2 5

With negative numbers a sliding window fails, so the code uses prefix sums and a count of earlier prefix values. [1, 2] and [3] give 2, and the five subarrays of [1, -1, 1, 1] that sum to 1 give 5.

More Python Programming questions

Exams that ask this topic