Workspace

Problem workspace

3 day streakD

Minimum Size Subarray Sum

MediumSliding WindowSmallest windows

The challenge

Return the minimum length of a contiguous subarray with sum at least target. Return 0 when no such subarray exists.

Positive integers only; target > 0. Empty input returns 0.

Example

[2, 3, 1, 2, 4, 3], target = 7 → 2, from [4, 3].

Use the walkthrough below to inspect the input and each state change.

See Minimum length sum, step by step

Expand, shrink, and inspect the window state.

6 elements · zero-based indicestarget = 7
Sliding window over 6 elementsThe current window is empty. Both boundaries move forward. Watch what enters, what leaves, and when the answer changes.Empty window · L = 0, R = -1203112234435
Current windowRecorded answerOutside window
Left
0
Right
-1
Length
0
Step 01 / 18

Start with an empty window

Both boundaries move forward. Watch what enters, what leaves, and when the answer changes.

left = 0; right = −1

Answer so far

0
View exact input

Input: [2,3,1,2,4,3] · target = 7

Current window is empty.

Put it into code

Positive values make expansion increase the sum and shrinking decrease it. Record a valid window before removing its left element.

Indices are zero-based. C++ uses C++17 or later.

def min_subarray_length(nums, target):
    # Positive integers; target > 0.
    left = total = 0
    best = len(nums) + 1
    for right, value in enumerate(nums):
        total += value
        while total >= target:
            best = min(best, right - left + 1)
            total -= nums[left]
            left += 1
    return 0 if best == len(nums) + 1 else best

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap