Patching Array - Problem

Given a sorted integer array nums and an integer n, you need to add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.

Return the minimum number of patches required.

The patching strategy should ensure that we can represent all integers from 1 to n using subsets of the modified array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3], n = 6
Output: 1
💡 Note: We can make [1,3,4] with the array. Missing 2,5,6. By patching 2, we can make [1,2,3,4,5,6]. Only 1 patch needed.
Example 2 — Empty Array
$ Input: nums = [1,5,10], n = 20
Output: 2
💡 Note: With [1,5,10], we can make some sums but need patches. We need to patch 2 and 4 to cover [1,20].
Example 3 — No Patches Needed
$ Input: nums = [1,2,2], n = 5
Output: 0
💡 Note: We can make [1,2,3,4,5] using subsets: 1→[1], 2→[2], 1+2→[3], 2+2→[4], 1+2+2→[5]. No patches needed.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 104
  • nums is sorted in ascending order
  • 1 ≤ n ≤ 231 - 1

Visualization

Tap to expand
Patching Array ProblemInput: nums = [1,3], n = 613Original arrayTarget: Cover all numbers [1, 6]123456✓ Available✗ MissingAfter patching with [2]:123456Answer: 1 patch needed
Understanding the Visualization
1
Input
Sorted array nums and target range [1, n]
2
Process
Find minimum patches to cover all numbers
3
Output
Number of patches required
Key Takeaway
🎯 Key Insight: If we can make sums [1, x], adding y extends to [1, x+y]. Greedily patch gaps!
Asked in
Google 15 Amazon 8 Facebook 6
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen