Length of the Shortest Subarray With Sum at Least a Target

Quick Overview

Find the length of the shortest contiguous subarray of positive integers whose sum is at least a target, or return 0 when none exists. It tests the sliding window technique on positive arrays and the reasoning behind why a two-pointer scan runs in linear time.

Length of the Shortest Subarray With Sum at Least a Target

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

Given an array of positive integers `nums` and a positive integer `target`, return the minimal length of a subarray whose sum is greater than or equal to `target`. If there is no such subarray, return `0` instead. A subarray is a contiguous non-empty sequence of elements within an array. ### Function Signature ```python def min_subarray_len(target: int, nums: list[int]) -> int: ``` ### Constraints - `1 <= target <= 10^9` - `1 <= len(nums) <= 10^5` - `1 <= nums[i] <= 10^4` ### Examples ```text Input: target = 7, nums = [2, 3, 1, 2, 4, 3] Output: 2 ``` The subarray `[4, 3]` sums to 7. No single element reaches 7, because the largest element is 4. ```text Input: target = 4, nums = [1, 4, 4] Output: 1 ``` The single element `[4]` already sums to 4. ```text Input: target = 11, nums = [1, 1, 1, 1, 1, 1, 1, 1] Output: 0 ``` The whole array sums to 8, so no subarray reaches 11.

Overview: Find the length of the shortest contiguous subarray of positive integers whose sum is at least a target, or return 0 when none exists. It tests the sliding window technique on positive arrays and the reasoning behind why a two-pointer scan runs in linear time.

Nov 24, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

A subarray is a contiguous non-empty sequence of elements within an array.

Function Signature

def min_subarray_len(target: int, nums: list[int]) -> int:

Constraints

  • 1 <= target <= 10^9
  • 1 <= len(nums) <= 10^5
  • 1 <= nums[i] <= 10^4

Examples

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

The subarray [4, 3] sums to 7. No single element reaches 7, because the largest element is 4.

Input: target = 4, nums = [1, 4, 4]
Output: 1

The single element [4] already sums to 4.

Input: target = 11, nums = [1, 1, 1, 1, 1, 1, 1, 1]
Output: 0

The whole array sums to 8, so no subarray reaches 11.