Patching Array (LeetCode 330): Solution and Explanation
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
- Set
reach = 0(64-bit),patches = 0,i = 0. - While
reach < n, look atnums[i]if any remain. - If
nums[i] <= reach + 1, setreach += nums[i]and advancei. - Otherwise patch with
reach + 1: setreach += reach + 1and incrementpatches. - Return
patchesoncereach >= n.
Step-by-step example
nums = [1,3], n = 6
- reach = 0. Card 1 is at most reach + 1 = 1, so use it: reach = 1.
- Card 3 is bigger than reach + 1 = 2, so 2 can never be formed from the cards. Patch with 2: reach = 3, patches = 1.
- Card 3 is at most reach + 1 = 4, so use it: reach = 6.
- 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 patches1class Solution {
2 public int minPatches(int[] nums, int n) {
3 long reach = 0;
4 int patches = 0;
5 int i = 0;
6 while (reach < n) {
7 if (i < nums.length && nums[i] <= reach + 1) {
8 reach += nums[i];
9 i++;
10 } else {
11 reach += reach + 1;
12 patches++;
13 }
14 }
15 return patches;
16 }
17}1class Solution {
2public:
3 int minPatches(vector<int>& nums, int n) {
4 long long reach = 0;
5 int patches = 0;
6 int i = 0;
7 while (reach < n) {
8 if (i < (int)nums.size() && nums[i] <= reach + 1) {
9 reach += nums[i];
10 i++;
11 } else {
12 reach += reach + 1;
13 patches++;
14 }
15 }
16 return patches;
17 }
18};Time and space complexity
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.
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
reachin a 32-bit int. With n = 2^31 - 1 the last patch can pushreachto 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 alwaysreach + 1. - Stopping when
numsruns out. Ifreach < nafter the last card, keep patching. - Using
nums[i] < reach + 1instead of<=. A card equal toreach + 1fills 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.