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
Difficulty
and has an acceptance rate of about 52% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Prefix Sum
- Sliding Window
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 76: Minimum Window Substring
- problem 718: Maximum Length of Repeated Subarray
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
Extra
- 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