datarekha
Coding Patterns Medium Asked at AmazonAsked at Google

Find the minimum length of a contiguous subarray whose sum is at least a given target.

The short answer

Use a variable sliding window: expand the right boundary to grow the sum, and once the sum meets the target, shrink from the left as much as possible while still staying at or above the target. Record the window length each time it qualifies. One O(n) pass.

How to think about it

The interviewer wants to know if you can spot a sliding window and, just as important, justify why it’s allowed. The brute-force answer — try every start-and-end pair and sum each — is O(n²) and the thing they hope you’ll walk past. The phrase that should trigger you is “shortest contiguous window meeting a sum condition” over positive integers. That positivity is the load-bearing detail: with all-positive values, adding an element can only grow the sum and removing one can only shrink it, and that monotonicity is precisely what makes the window safe to slide.

The mechanism is two boundaries that both move only rightward. You grow the window by advancing right, adding each new element to a running window_sum. The instant the sum reaches the target, you stop growing and start shrinking: record the current length, drop nums[left], advance left, and keep shrinking as long as the sum still qualifies. The moment it drops below target, you go back to growing. Each shrink finds the shortest valid window ending at the current right; because the values are positive, shrinking can only lower the sum, so you stop at exactly the right place. Every element enters the window once and leaves once, which is why two nested-looking boundaries still total a single linear pass.

A worked example

def min_subarray_len(target, nums):
    left = 0
    window_sum = 0
    best = float("inf")
    for right in range(len(nums)):
        window_sum += nums[right]            # grow on the right
        while window_sum >= target:          # qualified? shrink from the left
            best = min(best, right - left + 1)
            window_sum -= nums[left]
            left += 1
    return 0 if best == float("inf") else best

print(min_subarray_len(7, [2, 3, 1, 2, 4, 3]))   # shortest window summing >= 7
print(min_subarray_len(4, [1, 4, 4]))            # a single element already qualifies
print(min_subarray_len(11, [1, 1, 1, 1, 1]))     # whole array sums to 5, impossible
print(min_subarray_len(1, [0, 0, 5, 0]))         # one positive element suffices
2
1
0
1

The first case is the one to narrate. As right sweeps [2, 3, 1, 2, 4, 3], the window first hits the target at [2, 3, 1, 2] (sum 8), then shrinks; later [4, 3] gives sum 7 at length 2, the shortest qualifying window, so the answer is 2. The third case returns 0 by design: the entire array sums to only 5, never reaching 11, and best stays at infinity, which the final line maps to the sentinel 0 meaning “no such window.”

Keep practising

All Coding Patterns questions

Explore further

Skip to content