Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Find the smallest length of a contiguous block of positive integers whose sum is at least s (0 if none).

Problem: Find the smallest length of a contiguous block of positive integers whose sum is at least s (0 if none).
def min_len(a, s):
    l = total = 0
    best = float('inf')
    for r, x in enumerate(a):
        total += x
        while total >= s:
            best = min(best, r - l + 1)
            total -= a[l]
            l += 1
    return 0 if best == float('inf') else best
print(min_len([2, 3, 1, 2, 4, 3], 7), min_len([1, 1, 1], 5))
What is printed?
  1. A. 3 0
  2. B. 2 0
  3. C. 2 3
  4. D. 1 0

Correct answer: B. 2 0

Variable window: grow on the right, shrink while the sum is still ≥ s. [4, 3] reaches 7 with length 2. The second array never reaches 5, so the sentinel inf is turned into 0. Every index is added and removed once – O(n). The trick needs positive values.

More Coding Interview Problems questions

Exams that ask this topic