ProgrammingVery hardAmazon OA · Flipkart coding round
What is printed?
What is printed?
def at_most(a, k):
l = s = c = 0
for r, x in enumerate(a):
s += x
while s > k:
s -= a[l]
l += 1
c += r - l + 1
return c
def exact(a, k):
return at_most(a, k) - at_most(a, k - 1)
print(exact([1, 2, 1, 2, 1], 3), exact([1, 1, 1], 2))- A. 3 2
- B. 4 3
- C. 4 2
- D. 5 2
Correct answer: C. 4 2
With non-negative values, subarrays with sum at most k can be counted by a sliding window. Exact count equals at_most(k) minus at_most(k-1), giving 4 for the first array and 2 for the second.
More Python Programming questions
- What is printed? python from itertools import accumulate a = [3, 1, 4, 1, 5, 9, 2] print(list(accumulate(a, max)), list(accumulate(a…
- What is printed? python def comps(n, edges): p = list(range(n)) def find(x): while p[x] != x: p[x] = p[p[x]] x = p[x] return x cnt = n for…
- What is printed? python def spiral(m): out = [] while m: out += m.pop(0) m = [list(r) for r in zip(m)][::-1] return out print(spiral([[1…
- What is printed? python def climb(n, steps): dp = [0] (n + 1) dp[0] = 1 for i in range(1, n + 1): for s in steps: if i - s >= 0: dp[i] +=…
- What is printed? python from collections import deque def rot(g): R, C = len(g), len(g[0]) q = deque() fresh = 0 for r in range(R): for c…
- What is printed? python import heapq a, b, c = [1, 4, 7], [2, 5], [0, 3, 6] print(list(heapq.merge(a, b, c))[:5], next(heapq.merge(b, a)))