Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Smallest length of a contiguous subarray of POSITIVE integers with sum ≥ target (0 if none).
Problem: Smallest length of a contiguous subarray of POSITIVE integers with sum ≥ target (0 if none).
def minlen(a, t):
l, s, best = 0, 0, float('inf')
for r, x in enumerate(a):
s += x
while s >= t:
best = min(best, r - l + 1); s -= a[l]; l += 1
return 0 if best == float('inf') else best
print(minlen([5, 1, 3, 5, 10, 7, 4, 9, 2, 8], 15), minlen([1, 1, 1], 5))What is printed?- A. 3 0
- B. 1 0
- C. 2 3
- D. 2 0
Correct answer: D. 2 0
Positive values make the window sum monotone, so two pointers work in O(n). [10, 7] already sums to 17 ≥ 15, giving length 2 (no single value reaches 15). For [1, 1, 1] the total 3 never reaches 5, so the function returns 0, not 3.
More Coding Interview Problems questions
- Problem: Return all start indices of anagrams of p inside s using a fixed-size window of letter counts. python from collections import…
- Problem: Intersect two lists of disjoint, sorted closed intervals. python def inter(A, B): i = j = 0; out = [] while i < len(A) and j <…
- Problem: Cars drive toward a target on a one-lane road. A car that catches a slower car ahead joins it as a fleet (moving at the slower…
- Problem: Return the minimum number of parentheses to insert to make a string valid. python def minadd(s): open, add = 0, 0 for c in s: if…
- Problem: A ramp is a pair i < j with a[i] ≤ a[j]; its width is j − i. Find the maximum width using a decreasing stack of candidate left…
- Problem: Return the k most frequent words, ties broken alphabetically. python from collections import Counter def topk(words, k): c =…