Problem 209

Abstract / Summary

Find the smallest length of a group of consecutive numbers whose total is at least a given target value.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0209.py

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        left = 0
        sum  = 0
        result = float("inf")
        for right in range(len(nums)):
            # grow
            sum += nums[right]

            # shrink
            while sum - nums[left] >= target:
                sum  -= nums[left]
                left += 1

            if sum >= target:
                result = min(result, right - left + 1)

        return result if result < float("inf") else 0
18 lines | 524 bytes | submitted August 31, 2023 | GitHub   15% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Prefix Sum
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “minimum size sub-array sum” problem. It receives a target sum and an integer array, then determines the smallest length of a contiguous sub-array whose elements add up to at least the target. If no such sub-array exists, the function returns 0. The algorithm follows a sliding-window technique, expanding the right boundary of the window while maintaining a running sum, and shrinking the left boundary whenever the window can be made smaller without dropping below the target.

Initialization

The method begins by establishing three variables: left marks the start index of the current window, sum accumulates the total of elements inside the window, and result holds the best (smallest) length found so far, initialized to positive infinity. This setup prepares the sliding window for linear traversal of the input list.

left = 0
sum  = 0
result = float("inf")

Expanding the Window

A for loop iterates over each index right of the input array. At each iteration the element at right is added to sum, effectively extending the window to include the new element. This step ensures that every possible right boundary is examined exactly once.

for right in range(len(nums)):
    sum += nums[right]          # grow

Shrinking the Window

After the window has been grown, a while loop attempts to contract it from the left side. The condition checks whether removing the element at left would still keep the window sum at least equal to the target. If so, the element is subtracted from sum and left is advanced. This loop runs until the window cannot be reduced further without violating the target constraint, guaranteeing that the window is as tight as possible for the current right.

while sum - nums[left] >= target:
    sum  -= nums[left]
    left += 1

Updating the Best Length

Once the window cannot be shrunk any more, the algorithm checks whether the current sum meets or exceeds the target. If it does, the length of the window (right - left + 1) is a candidate for the minimal length. result is updated with the smaller of its current value and this candidate length.

if sum >= target:
    result = min(result, right - left + 1)

Final Result Determination

After the loop finishes, the method examines whether a valid sub-array was ever found. If result remains infinite, it means no window satisfied the target, and the function returns 0. Otherwise, it returns the smallest length recorded.

return result if result < float("inf") else 0

Edge Cases Handled

The algorithm gracefully handles an empty input list: the for loop never executes, result stays infinite, and the final conditional returns 0. When the target is zero or negative, the initial sum of zero already satisfies the condition, but the loop logic still proceeds correctly, ultimately yielding a length of 1 for the first element (or 0 if the list is empty). If the target exceeds the sum of all elements, the shrinking step never produces a qualifying window, and the function correctly returns 0. The while-shrink condition uses sum - nums[left] >= target, which prevents an out-of-range access when left reaches right, because the loop only runs while there is at least one element to remove.

Performance Optimizations

The sliding-window approach ensures that each element is added to sum exactly once and removed at most once. Consequently, the total number of pointer movements (right and left) is bounded by twice the length of the array, yielding a linear traversal without nested full-array scans. The use of a running sum avoids recomputing sub-array totals, and the direct comparison with float("inf") eliminates the need for separate flags to indicate whether a valid window was found. These choices keep the algorithm efficient for large inputs.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train track made of many colorful blocks, and each block has a number written on it. The goal is to find the shortest segment of track where all the numbers added together reach a specific target weight.

Think of two little markers, one on the left and one on the right, that slide along the track to look at a slice of those blocks. To start, both markers sit at the beginning. The right marker moves forward one block at a time, grabbing the numbers and adding them to a pile. Every time a new block is added, the pile gets bigger.

Once the pile is heavy enough to reach the target, it is time to check if the slice can be made smaller. The left marker tries to sneak away by removing blocks from the start of the pile one by one. As long as the pile stays heavy enough even after taking a block away, the left marker happily moves forward, making the slice shorter.

Whenever the pile is heavy enough to meet the target, the length of the current slice is measured. This length is written down if it is shorter than any other slice found so far. The right marker then continues to move forward, adding more blocks to explore, while the left marker waits for the next chance to shrink the slice again. This continues until the end of the track is reached, and the smallest length found during the trip is what matters.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.11 | σ = 1.26

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust C# Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JS
fartem Ruby
fengvyi C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
lennylxx C
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
fengvyi C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
lennylxx C
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
52 links | 36 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode Minimum Size Subarray Sum Solution Explained - Java'
Nick White 9 mins
LeetCode Minimum Size Subarray Sum Solution Explained - Java
YouTube video 'Minimum Size Subarray Sum | Google | Amazon | Easy Explanation | codestorywithMIK'
codestorywithMIK 19 mins
Minimum Size Subarray Sum | Google | Amazon | Easy Explanation | codestorywithMIK
YouTube video 'Minimum Size Subarray Sum (LeetCode 209) | Full solution with animations | Variable Sliding Window'
Nikhil Lohia 18 mins
Minimum Size Subarray Sum (LeetCode 209) | Full solution with animations | Variable Sliding Window
YouTube video '[Java] Leetcode 209. Minimum Size Subarray Sum [Sliding Window #1]'
Eric Programming 11 mins
[Java] Leetcode 209. Minimum Size Subarray Sum [Sliding Window #1]
YouTube video 'Minimum Size Subarray Sum - Leetcode 209 - Sliding Window (Python)'
Greg Hogg 7 mins
Minimum Size Subarray Sum - Leetcode 209 - Sliding Window (Python)
YouTube video 'LeetCode 209 -  Minimum Size Subarray Sum'
Engineering Digest 8 mins
LeetCode 209 - Minimum Size Subarray Sum
YouTube video '209. Minimum Size Subarray Sum | LEETCODE MEDIUM | SLIDING WINDOW'
code Explainer 10 mins
209. Minimum Size Subarray Sum | LEETCODE MEDIUM | SLIDING WINDOW
YouTube video 'LeetCode 209. Minimum Size Subarray Sum'
Happy Coding 13 mins
LeetCode 209. Minimum Size Subarray Sum
YouTube video 'Minimum Size Subarray Sum | Two Pointers | Leetcode 209'
Pepcoding 33 mins
Minimum Size Subarray Sum | Two Pointers | Leetcode 209
YouTube video 'Leetcode | 209. Minimum Size Subarray Sum | Medium | Java Solution'
Developer Docs 10 mins
Leetcode | 209. Minimum Size Subarray Sum | Medium | Java Solution
YouTube video 'Minimum Size Subarray Sum - LeetCode 209 - Coding Interview Questions'
One Code Man 6 mins
Minimum Size Subarray Sum - LeetCode 209 - Coding Interview Questions
YouTube video 'Leetcode 209 Minimum Size Subarray Sum'
Jeevan Kumar - Cracckify 8 mins
Leetcode 209 Minimum Size Subarray Sum
YouTube video 'Minimum Size Subarray Sum - 209. LeetCode - C#'
Teddy Smith 13 mins
Minimum Size Subarray Sum - 209. LeetCode - C#
YouTube video 'Leetcode 209: Minimum Size Subarray Sum in Telugu | Brute Force, Sliding Window | srkcodes'
Srk Codes 16 mins
Leetcode 209: Minimum Size Subarray Sum in Telugu | Brute Force, Sliding Window | srkcodes
YouTube video '209 || Minimum Size Subarray Sum II || C++ || Leetcode Daily Challenge'
CodeFreaks 14 mins
209 || Minimum Size Subarray Sum II || C++ || Leetcode Daily Challenge
YouTube video 'LeetCode 209. Minimum Size Subarray Sum (2nd time)'
Happy Coding 20 mins
LeetCode 209. Minimum Size Subarray Sum (2nd time)
YouTube video 'LeetCode 209: Minimum Size Subarray Sum | Java Solution | Sliding Window'
Code Scribbler 10 mins
LeetCode 209: Minimum Size Subarray Sum | Java Solution | Sliding Window
YouTube video 'Leetcode 209 - Minimum Size Subarray Sum (JAVA Solution Explained!)'
LC Bear 9 mins
Leetcode 209 - Minimum Size Subarray Sum (JAVA Solution Explained!)
YouTube video 'Minimum Size Subarray Sum - Sliding Window - Leetcode 209 - Python and Java'
CSTutor Center 27 mins
Minimum Size Subarray Sum - Sliding Window - Leetcode 209 - Python and Java
YouTube video 'Daily Leetcode #1192: Jul 06, 2023 - 209. Minimum Size Subarray Sum'
Programming Live with Larry 12 mins
Daily Leetcode #1192: Jul 06, 2023 - 209. Minimum Size Subarray Sum
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

27 solutions   August 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality