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?
  1. A. 3 0
  2. B. 1 0
  3. C. 2 3
  4. 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

Exams that ask this topic