Data Structures & AlgorithmsModerateCodeforces Div2 B · two pointers

Problem: What is the minimum length of a contiguous subarray of [1, 2, 3, 4, 5, 6, 7, 8] with sum at least 15? Run the two-pointer code.

Problem: What is the minimum length of a contiguous subarray of [1, 2, 3, 4, 5, 6, 7, 8] with sum at least 15? Run the two-pointer code.
a = [1, 2, 3, 4, 5, 6, 7, 8]
l = s = 0
best = float('inf')
for r, x in enumerate(a):
    s += x
    while s >= 15:
        best = min(best, r - l + 1)
        s -= a[l]
        l += 1
print(best)
What is printed?
  1. A. 2
  2. B. 3
  3. C. 1
  4. D. 4

Correct answer: A. 2

The pair 7 + 8 = 15 is the shortest window reaching 15, and no single element is that large.

More Coding Interview Problems questions

Exams that ask this topic