Patching Array (LeetCode 330): Solution and Explanation

Hard
Array
Greedy

Add as few numbers as possible to a sorted array so that every value from 1 to n is the sum of some subset. The whole problem collapses to one number: the largest reach such that everything in [1, reach] is already formable.

Intuition

Say the numbers used so far can form every sum from 1 to reach. Take a new number x. Every old sum plus x is now also formable, which covers [x, reach + x]. If x <= reach + 1, that range touches the old one, so the covered range becomes the single block [1, reach + x] with no holes.

If instead x > reach + 1, the value reach + 1 is a hole. Every remaining number in nums is at least x, so none of them can fill it. Some patch has to.

Which patch? Any patch p <= reach + 1 closes the hole and extends coverage to reach + p. The largest legal choice, p = reach + 1, extends it the most, to 2 * reach + 1. A bigger range can only make later decisions easier, so this choice is never worse.

Each patch at least doubles the reach, so at most about 31 patches are needed even for n = 2^31 - 1.

Approach: Greedy reach with doubling patches

  1. Set reach = 0 (64-bit), patches = 0, i = 0.
  2. While reach < n, look at nums[i] if any remain.
  3. If nums[i] <= reach + 1, set reach += nums[i] and advance i.
  4. Otherwise patch with reach + 1: set reach += reach + 1 and increment patches.
  5. Return patches once reach >= n.

Step-by-step example

nums = [1,3], n = 6
  1. reach = 0. Card 1 is at most reach + 1 = 1, so use it: reach = 1.
  2. Card 3 is bigger than reach + 1 = 2, so 2 can never be formed from the cards. Patch with 2: reach = 3, patches = 1.
  3. Card 3 is at most reach + 1 = 4, so use it: reach = 6.
  4. reach = 6 >= n, so stop. The answer is 1.

Code: Python, Java, C++

1class Solution:
2    def minPatches(self, nums: List[int], n: int) -> int:
3        reach = 0
4        patches = 0
5        i = 0
6        while reach < n:
7            if i < len(nums) and nums[i] <= reach + 1:
8                reach += nums[i]
9                i += 1
10            else:
11                reach += reach + 1
12                patches += 1
13        return patches
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m + log n)

Each iteration either consumes one of the m numbers or adds a patch, and patches at least double reach, so there are at most about log2(n) of them.

Space

O(1)

Only reach, the index and the counter are stored.

Other approaches

Subset-sum bitset (time O(n * (m + patches)), space O(n))

Track every formable sum in a bitset and add the smallest missing value as a patch. It works for small n but needs n bits of memory and O(n) per update, which is hopeless for n near 2^31.

Common mistakes

  • Storing reach in a 32-bit int. With n = 2^31 - 1 the last patch can push reach to about 2^32, which overflows and loops forever.
  • Patching with the first missing number found by brute force instead of reasoning about reach. The greedy patch is always reach + 1.
  • Stopping when nums runs out. If reach < n after the last card, keep patching.
  • Using nums[i] < reach + 1 instead of <=. A card equal to reach + 1 fills the hole by itself.

Frequently asked questions

Why is patching with reach + 1 optimal?

The patch must be at most reach + 1, or reach + 1 stays unformable. Among those choices, reach + 1 gives the largest new range, and a larger covered range never forces more patches later.

Why does adding x <= reach + 1 leave no holes?

Old sums cover [1, reach] and old sums plus x cover [x, reach + x]. Since x <= reach + 1, the second block starts no later than one past the end of the first, so together they form [1, reach + x].

How many patches can there be at most?

Each patch turns reach into 2 * reach + 1, so after k patches reach is at least 2^k - 1. About 31 patches suffice for any n up to 2^31 - 1.