InteractLab

InteractLabProblem WalkthroughsSmallest Subarray with Sum ≥ Target

Smallest Subarray with Sum ≥ Target

Find the shortest run of neighbouring numbers that adds up to at least the target.

Sliding WindowTwo PointersArrays
ProblemWhat are we solving?

You are given a list of positive numbers and a target.

Find the length of the shortest contiguous block (a run of side-by-side numbers) whose sum is greater than or equal to the target.

If no block reaches the target, the answer is infinity — there is no valid window.

ExamplesWorked cases
in: nums = [2, 1, 5, 2, 3, 2], target = 7
out: 2

The block [5, 2] adds up to 7 and has length 2. No single number reaches 7, so 2 is the shortest.

in: nums = [3, 4, 1, 1, 6], target = 6
out: 1

The single number 6 already meets the target, so the shortest window has length 1.

in: nums = [1, 1, 1], target = 9
out: infinity

Even the whole list only sums to 3, so no window ever reaches 9.

WalkthroughStep by step
201152233425left
left0
right
current_sum0
min_len
Python
1def smallest_window(nums, target):2    left = 03    current_sum = 04    min_len = infinity5    for right in range(len(nums)):6        current_sum += nums[right]7        while current_sum >= target:8            min_len = min(min_len, right - left + 1)9            current_sum -= nums[left]10            left += 111    return min_len
Step 1 / 38SetupWe start with a window that has no width yet. left marks the start of the window and sits at index 0.
1 / 38
Space play/pause · step · Home/End jump · R replay
CostTime & space
timeO(n)spaceO(1)

left and right each only move forward, so every number is added once and removed at most once — one pass, not a nested scan.