Back to Problem
Official 1732 views

Editorial: Shortest Subarray With Sum ≥ Target

by admin ·

9

1 Intuition

With positive numbers, growing the window only increases its sum.

2 Approach

Extend the right end; while the sum reaches the target, record the length and shrink from the left.

3 Complexity Analysis

Time O(n), Space O(1).

4 Solution Code

class Solution:
    def minSubArrayLen(self, target: int, nums: list[int]) -> int:
        best, total, lo = float('inf'), 0, 0
        for hi, x in enumerate(nums):
            total += x
            while total >= target:
                best = min(best, hi - lo + 1)
                total -= nums[lo]
                lo += 1
        return 0 if best == float('inf') else best

5 Code Walkthrough

The reference solution below implements the approach step by step.