Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the minimum size subarray with sum at least a target

Given an array of positive integers and a target sum, find the minimal length of a contiguous subarray whose sum is at least the target.

Python practice17 minTwo Pointers & Sliding WindowIntermediateLast updated March 26, 2026

Problem statement

Given a positive integer target and an array of positive integers nums, return the minimal length of a contiguous subarray [nums[l], nums[l+1], ..., nums[r]] of which the sum is at least target. If there is no such subarray, return 0. Use a sliding-window (two-pointer) approach that expands the right end and contracts the left end to maintain sums efficiently.

Task

Use the sliding window technique to find the smallest contiguous subarray whose sum >= target in O(n) time.

Examples

Example

Input

target = 7, nums = [2,3,1,2,4,3]

Output

2

The subarray [4,3] has the minimal length 2 with sum >= 7.

Input format

Two arguments: an integer target and a list of positive integers nums.

Output format

Return an integer representing the minimal length of a contiguous subarray with sum at least target; return 0 if none exists.

Constraints

1 <= len(nums) <= 10^5, 1 <= nums[i] <= 10^5, 1 <= target <= 10^9. Time target: O(n), extra space: O(1).

Samples

Sample 1

Input

target = 4, nums = [1,4,4]

Output

1

Single element 4 meets the target; minimal length is 1.