⚡Flashcard Drill➔
NeetCode #238LC-209MediumSliding WindowNC 250
← Back to All Problems

#238 · #209 · Minimum Size Subarray Sum(长度最小的子数组)

📌 Problem Statement & Constraints

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is at least target. If none exists, return 0. Constraints: 1 <= nums.length <= 10^5, 1 <= nums[i] <= 10^4, 1 <= target <= 10^9.

💡 Core Algorithmic Approaches

  1. All values are positive, so the window sum is monotone in both directions -- a sliding window applies.
  2. Expand the right end, adding to the running sum.
  3. While the sum is at least target, record the window length and shrink from the left.
  4. Because the sum only decreases when shrinking, the inner loop is amortised O(n) overall.

💻 Benchmark Python3 Implementation

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        l = 0
        cur = 0
        best = float("inf")
        for r, x in enumerate(nums):
            cur += x
            while cur >= target:       # valid -> try to shrink
                best = min(best, r - l + 1)
                cur -= nums[l]
                l += 1
        return best if best != float("inf") else 0

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each element enters and leaves the window at most once.
💾 Space Complexity
O(1): three scalars.

⚠️ Interview Pitfalls & Follow-ups

  • Using this approach with negative numbers: the monotonicity of the window sum is what makes it valid, and the constraints guarantee positivity. For general values, prefix sums with a hash map are needed.
  • Using > target instead of >=: the requirement is *at least* target.
  • Returning best when no window qualifies: it would be inf; the sentinel check converts it to 0.
  • Shrinking only once instead of in a while loop: the minimal window requires shrinking as far as possible.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

长度最小的子数组

给定一个含有 n 个正整数的数组和一个正整数 target。找出该数组中满足其总和大于等于 target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr−1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0。约束:1 ≤ target ≤ 10^9;1 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^4。

核心要点

  • 变长滑动窗口(标准解) :维护窗口和 total 。右指针扩展窗口;当 total &gt;= target 时更新答案并收缩左边界。
  • 为什么可以用滑动窗口 :数组元素 全为正数 ,因此窗口和随右扩而增、随左缩而减,具有单调性,收缩条件成立。
  • 关键约束 :若数组含负数或零,窗口和不再单调,滑动窗口会失效(需改用前缀和 + 二分或单调队列)。
  • 复杂度 :左右指针各自单调前进,O(n)。

常见陷阱

  • 用 while total &gt; target 而非 &gt;= :题目要求「大于等于」,用 &gt; 会漏掉恰好等于的情况。
  • 收缩时忘记减去 nums[l] :会导致窗口和与实际不符。
  • 不存在时返回 best (inf) :必须返回 0。
  • 数组含负数时仍用滑动窗口 :本题约束为正整数,因此可用;若含负数则需换算法。
  • 用前缀和 + 双重循环 :O(n²) 会超时;若要用前缀和,应配合二分(前缀和单调递增)做到 O(n log n)。

参考实现

class Solution:
    def minSubArrayLen(self, target: int, nums: list[int]) -> int:
        l = 0
        total = 0
        best = float('inf')
        for r, x in enumerate(nums):
            total += x
            while total >= target:          # 满足条件 -> 尝试收缩
                if r - l + 1 < best:
                    best = r - l + 1
                total -= nums[l]
                l += 1
        return 0 if best == float('inf') else best