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))- A. 2 4
- B. 3 5
- C. 2 5
- 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
- What is printed? python def twotx(p): b1 = b2 = float('-inf') s1 = s2 = 0 for x in p: b1 = max(b1, -x) s1 = max(s1, b1 + x) b2 = max(b2…
- What is printed? python def tile(n): dp = [0] (n + 1) dp[0] = 1 for i in range(1, n + 1): dp[i] = dp[i - 1] + (dp[i - 2] if i >= 2 else 0)…
- A program sorts the whole list again for each of 10^5 queries on a list of 10^5 items. Which statement about running it in CPython is…
- What is printed? python from collections import Counter def mw(s, t): need = Counter(t) have = {} formed = 0 req = len(need) l = 0 best =…
- What is printed? python import bisect board = [] for name, score in [('a', 5), ('b', 9), ('c', 5)]: bisect.insort(board, (-score, name))…
- What is printed? python print(sum([1, 2], 0.5))