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))- A. 7
- B. 6
- C. 5
- 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
- What is printed? python from collections import deque g = ['..#', '.##', '...'] def bfs(g): R, C = len(g), len(g[0]) d = {(0, 0): 0} q =…
- What is printed? python from functools import lrucache calls = 0 @lrucache(maxsize=None) def f(n): global calls calls += 1 if n < 2…
- What is printed? python def greedy(coins, amt): cnt = 0 for c in sorted(coins, reverse=True): cnt += amt // c amt %= c return cnt if amt…
- What is printed? python import bisect def lis(a): t = [] for x in a: i = bisect.bisectleft(t, x) if i == len(t): t.append(x) else: t[i] =…
- A list a is sorted in ascending order and may contain duplicates. Using bisectleft and bisectright from the bisect module, which…
- A Python list q holds n items. A loop repeatedly does x = q.pop(0) until q is empty. What is the total time cost of the loop in big-O terms?