Patching Array
Master this topic with zero to advance depth.
Patching Array
Add minimum elements to a sorted array so all numbers in [1, n] can be formed by sums.
Visual Representation
nums = [1, 3], n = 6
Reach: [1, 1] (via 1)
Next miss: 2. nums[i]=3 > 2. PATCH 2.
Reach: [1, 3] (via 1, 2)
Next miss: 4. nums[i]=3 <= 4. Use 3.
Reach: [1, 6] (via 1, 2, 3)
Done. Patches: 1Examples
Adding 2 allows forming sums up to 6.
Level I: Brute Force (Recursion / Subsets)
Intuition
Try all possible combinations of patches (numbers from 1 to n) and check if each subset sum can form all numbers in [1, n]. This is extremely slow but guaranteed to find the minimum patches.
Thought Process
isPossible(current_nums, n): Checks if all numbers in [1, n] can be formed.solve(current_nums, count): Recursively tries adding each possible numberpthat is not incurrent_nums.- Return the minimum
countsuch thatisPossibleis true.
Detailed Dry Run
nums = [1, 3], n = 6
- isPossible([1, 3], 6)? No (cannot form 2).
- Try adding 2: [1, 2, 3]. sums: 1, 2, 3, 4(1+3), 5(2+3), 6(1+2+3). YES. Min patches = 1.
Level II: Dynamic Programming (Boolean Knapsack)
Intuition
Treat this as a variation of the Subset Sum problem. For a given set of numbers, maintain a boolean array can_form where can_form[i] is true if sum i can be reached.
Thought Process
dp[i]= true if sumiis possible.- Start with original
nums. Updatedpfor each number. - If
dp[miss]is false for somemiss <= n, we must add a patch. - Greedy choice for patch is always the smallest missing number to maximize coverage.
Detailed Dry Run
nums = [1, 3], n = 6, dp=[T, F, F, F, F, F, F] (dp[0]=T)
- Use 1: dp=[T, T, F, F, F, F, F]
- Use 3: dp=[T, T, F, T, T, F, F]
- Miss = 2. Patch 2.
- Use 2: dp=[T, T, T, T, T, T, T]. DONE.
Level III: Optimal Greedy (Reachability Range)
Intuition
Maintain the smallest number miss that cannot be formed. If nums[i] <= miss, use it to extend the range. Otherwise, patch miss to double the reach.
Thought Process
miss= current gap.- If
nums[i] <= miss:miss += nums[i++]. - Else:
miss += miss,count++.
Pattern: Greedy Range Extension
Detailed Dry Run
nums = [1, 5, 10], n = 20 miss=1: Use 1, miss=2 miss=2: nums[1]=5 > 2. Patch 2, miss=4 miss=4: nums[1]=5 > 4. Patch 4, miss=8 miss=8: Use 5, miss=13 miss=13: Use 10, miss=23. DONE.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.