LeetCode 209: Minimum Size Subarray Sum — Python Solution

LeetCode 209: Minimum Size Subarray Sum is a Medium sliding window problem. This Python walkthrough develops a positive sliding window solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicSliding Window
Reusable patternpositive sliding window
ComplexityO(n) time and O(1) extra space

Recognizing the pattern

A sliding window fits when validity changes incrementally as the right edge expands and the left edge contracts.

For this problem specifically, expand until the positive-number sum reaches the target, then shrink as much as possible while recording the shortest valid length. The invariant worth writing beside the code is: Before each expansion, the current window is the shortest examined suffix for its right boundary.

Step-by-step algorithm

  1. Identify the input state consumed by minSubArrayLen(target, nums) and initialize the data required by the positive sliding window pattern.
  2. Expand until the positive-number sum reaches the target, then shrink as much as possible while recording the shortest valid length.
  3. After each update, verify the page’s central invariant: Before each expansion, the current window is the shortest examined suffix for its right boundary.
  4. Finish only after the boundary behavior is covered: Return zero when no window reaches the target.

Python solution

class Solution:
    def minSubArrayLen(self, target, nums):
        left = total = 0; best = len(nums) + 1
        for right, value in enumerate(nums):
            total += value
            while total >= target:
                best = min(best, right - left + 1)
                total -= nums[left]; left += 1
        return 0 if best > len(nums) else best

Reading the implementation

The main entry point is minSubArrayLen(target, nums). The named working state includes left, total, best; those variables make the positive sliding window state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, expand until the positive-number sum reaches the target, then shrink as much as possible while recording the shortest valid length.

Correctness argument

Initialization. Before the scan begins, the unresolved range contains every candidate and the processed range is empty, so no answer has been lost.

Preservation. Expand until the positive-number sum reaches the target, then shrink as much as possible while recording the shortest valid length. The chosen movement discards only candidates that cannot improve the answer; afterward, before each expansion, the current window is the shortest examined suffix for its right boundary.

Termination. A boundary advances on every iteration. Once the active range is exhausted, every viable candidate was either measured or safely eliminated, so the stored result is optimal.

Complexity and trade-offs

O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Enumerating every substring or subarray is conceptually simple but recomputes almost the same state for overlapping ranges. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().minSubArrayLen(7,[2,3,1,2,4,3]) == 2

Common mistakes and edge cases

  • Problem-specific boundary: Return zero when no window reaches the target.
  • Pattern-level pitfall: Update counts in the correct order when an item enters or leaves, especially when duplicate requirements are present.
  • Invariant check: after every update, confirm that before each expansion, the current window is the shortest examined suffix for its right boundary.

Interview review checklist

  • Explain why positive sliding window matches the structure of this input.
  • State the invariant in one sentence before tracing code: Before each expansion, the current window is the shortest examined suffix for its right boundary.
  • Derive O(n) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: Return zero when no window reaches the target.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 15. 3Sum · Next: 3. Longest Substring Without Repeating Characters