Problem 330

Abstract / Summary

Given a sorted list of positive integers and a target number, find the minimum number of patches needed so that every number up to the target can be formed by summing elements from the list or patches.

Note

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

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
19 lines | 630 bytes | submitted March 26, 2024 | GitHub   54% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
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 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.

written by openai gpt

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.

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 = 6 | μ = 5.63 | σ = 2.06

Complexity Analysis

not analyzed yet

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++ 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++
32 links | 18 authors | 8 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 hard
3 solutions   March 26, 2024

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