Python 1413.py
class Solution:
def minStartValue(self, nums: List[int]) -> int:
low = 0
have = 0
for n in nums:
have += n
low = min(low, have)
return 1 - low
Difficulty
and has an acceptance rate of about 65% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Prefix Sum
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 defines a class Solution with a single method minStartValue. The method receives a list of integers nums and computes the smallest positive integer that, when used as an initial cumulative sum, guarantees that the running total never drops below 1 while iterating through the list. The algorithm proceeds by scanning the list once, tracking the cumulative sum and the lowest value that this sum attains. At the end, it derives the required starting value from the recorded minimum.
Key Steps
The core logic consists of three distinct phases: initialization, iterative accumulation, and final calculation.
Initialization
low = 0
have = 0
Two integer variables are created. have will hold the running total as the list is processed, while low records the smallest value that have reaches during the scan. Both start at zero, which represents the baseline before any elements are added.
Iterative Accumulation
for n in nums:
have += n
low = min(low, have)
The method iterates over each element n in the input list. With each iteration, have is incremented by the current element, reflecting the cumulative sum up to that point. Immediately after updating have, the code updates low by comparing its current value with the new have. The min function ensures that low always holds the most negative (or smallest) cumulative sum encountered so far. This single pass captures the deepest dip of the running total, regardless of where it occurs in the sequence.
Final Calculation
return 1 - low
After the loop finishes, low contains the minimum cumulative sum observed. If low is non-negative, the running total never fell below zero, and the smallest starting value needed is simply 1. If low is negative, adding its absolute value to the starting point lifts the entire trajectory so that the lowest point becomes 1. Subtracting low from 1 accomplishes exactly this adjustment, yielding the minimal positive start value required.
Edge Cases Handled
The algorithm gracefully handles several boundary conditions without additional branching.
When the input list is empty, the loop body never executes, leaving low at its initial value of 0. The return expression then evaluates to 1 - 0, correctly returning 1 as the minimal start value, because no operations can cause the sum to drop below 1.
If all numbers in nums are non-negative, the cumulative sum never decreases, so low remains 0 throughout the iteration. The final expression again yields 1, reflecting that a starting value of 1 is sufficient.
Conversely, when the list contains negative numbers that drive the cumulative sum below zero, low captures the most negative point. For example, with nums = [-3, 2, -3, 4, 2], the cumulative sums are -3, -1, -4, 0, 2; the minimum is -4. The return value becomes 1 - (-4) = 5, which is the smallest start value that keeps the running total at least 1 throughout the sequence.
The method also works correctly when the minimum cumulative sum occurs at the very first element, at the very last element, or multiple times; the min operation updates low each time a new lower value appears, ensuring the final result reflects the deepest dip.
Performance Optimizations
The implementation achieves optimal efficiency by performing a single linear traversal of the input list. All necessary information-current cumulative sum and its minimum-are maintained in constant-size scalar variables, avoiding any auxiliary data structures. The use of the built-in min function for updating low is a lightweight operation that incurs minimal overhead. By computing the final answer directly from the recorded minimum, the code eliminates the need for a second pass or additional arithmetic after the loop. This design ensures that the method scales linearly with the length of nums while keeping memory usage minimal.
ELI5 - Simplified Explanation
Imagine holding a small bucket that starts with nothing inside. You are going on a walk along a path filled with numbers. Sometimes the numbers are big and fun, and you get to add them to your bucket. Other times, the numbers are sad and you have to take some away from your bucket.
The goal is to make sure your bucket never feels empty while you walk. If you start with a tiny bit of help, you can keep the bucket happy during the whole trip. This code looks at every single step on the path to see how low the bucket drops. If the path takes away more than you have, it remembers the deepest point where you were most worried about running out. By looking at that deepest point, you can figure out exactly how much help you needed at the very start to make sure the bucket stayed safe the entire time.
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++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | TS | |||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| varunu28 | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1460: Make Two Arrays Equal by Reversing Subarrays
- problem 1507: Reformat Date
- problem 1598: Crawler Log Folder
- problem 1944: Number of Visible People in a Queue
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