Python 0330.py
class Solution:
def minPatches(self, nums: List[int], n: int) -> int:
result = 0
# each sorted list is a min-heap
nums.append(n + 1) # avoid an empty heap
unknown = 1 # next number not yet formed
while unknown <= n:
# there is a gap, we can't build number "unknown"
if nums[0] > unknown:
# patch that number
heappush(nums, unknown)
result += 1
# we can add nums[0] to all already known numbers and thus extend our range
unknown += heappop(nums)
return result
Difficulty
and has an acceptance rate of about 55% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
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 patches” problem: given a sorted list of positive integers nums and a target n, determine the smallest number of additional integers that must be inserted so that every value in the range [1, n] can be expressed as a sum of some subset of the resulting list. The algorithm relies on a min-heap to always work with the smallest available element, and it incrementally expands the reachable interval [1, unknown) until unknown exceeds n.
Core Logic
The function begins by initializing a counter result that will hold the number of patches added.
result = 0
A sentinel value n + 1 is appended to nums. This guarantees that the heap is never empty during the main loop, eliminating the need for an explicit emptiness check.
nums.append(n + 1) # avoid an empty heap
The variable unknown is set to 1, representing the smallest positive integer that has not yet been constructible from the current set of numbers.
unknown = 1 # next number not yet formed
The algorithm then enters a loop that continues while unknown is less than or equal to n.
while unknown <= n:
...
Gap Detection and Patching
Inside the loop, the smallest element of the heap (nums[0]) is examined. If this element is larger than unknown, there exists a gap: the current collection cannot produce unknown. The algorithm resolves the gap by inserting unknown itself into the heap, effectively patching the missing value. The patch count is incremented.
if nums[0] > unknown:
heappush(nums, unknown)
result += 1
Extending the Reachable Range
Regardless of whether a patch was added, the smallest element is removed from the heap and added to unknown. This operation reflects the fact that any sum that could be formed before can now be extended by the popped value, thereby expanding the reachable interval.
unknown += heappop(nums)
When the loop terminates, unknown has surpassed n, meaning every integer up to n is now representable. The function returns the total number of patches required.
return result
Edge Cases Handled
When the original nums list is empty, the sentinel n + 1 ensures that the heap contains at least one element, allowing the algorithm to start patching from unknown = 1 without special-case logic.
If n is 0, the condition unknown <= n is false from the outset (unknown starts at 1), so the loop body never executes and the function correctly returns 0 patches.
When the smallest element of the original list is already 1, the gap detection condition fails, and the algorithm immediately uses that element to extend the reachable range, avoiding unnecessary patches.
If the input list already contains numbers that collectively cover the entire range up to n, the loop will consume those numbers one by one, each time expanding unknown until it exceeds n. No patches are added, and result remains 0.
Performance Optimizations
The use of a min-heap (heappush / heappop) guarantees that the smallest available number is always processed first, which is essential for the greedy expansion of the reachable interval. By always adding the smallest element to unknown, the algorithm maximizes the range growth per iteration, minimizing the total number of loop cycles.
Appending the sentinel n + 1 eliminates a conditional check for an empty heap on each iteration, reducing branch overhead. This small adjustment also prevents a potential IndexError when accessing nums[0].
The loop condition while unknown <= n provides an early exit as soon as the target range is covered, avoiding unnecessary heap operations once the goal is achieved.
All heap operations are performed in-place on the original nums list, avoiding the allocation of auxiliary data structures and thereby reducing memory pressure.
Overall, the algorithm achieves a tight, linear progression through the required range, leveraging the heap to maintain optimal ordering while keeping auxiliary work to a minimum.
ELI5 - Simplified Explanation
Imagine you are playing with a set of blocks that each have a different number written on them. You want to be able to build every single number from one all the way up to a big number like ten. Sometimes, you might find that you are missing a piece that stops you from building the next number in line.
The code starts by keeping track of the smallest number you cannot build yet, which starts at one. It looks at your pile of blocks to see if you have the one you need. If your pile does not have that specific number, you have to go get a brand new block to fill that gap. Every time you add a new block to your pile, you count it as a patch and the range of numbers you can build gets much bigger.
The computer keeps checking if there are any gaps while the number you want to build is still smaller than or equal to the big goal number. By taking the smallest block from the pile and adding it to your total, you discover even more numbers that you can now reach. It keeps going like this until all the numbers up to the big goal are covered.
Code Quality
Complexity Analysis
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 | Go | Python | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| MemoryLimitExceeded | C++ | Python | |||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| ruoru | Rust | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| ruoru | Rust | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 1798: Maximum Number of Consecutive Values You Can Make
Solved On The Same Day
- problem 335: Self Crossing
- problem 363: Max Sum of Rectangle No Larger Than K
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