Patching Array - Problem
You're given a sorted integer array
Think of it as filling gaps in your ability to represent numbers. If you can represent all numbers from 1 to
Goal: Return the minimum number of patches required to make all numbers in range [1, n] representable.
Example: For
nums and an integer n. Your mission is to strategically patch (add) the minimum number of elements to the array so that any number from 1 to n can be formed by summing some elements in the array.Think of it as filling gaps in your ability to represent numbers. If you can represent all numbers from 1 to
miss-1, but can't represent miss, you need to add miss to your array to extend your range.Goal: Return the minimum number of patches required to make all numbers in range [1, n] representable.
Example: For
nums = [1, 3] and n = 6, you can represent 1, 3, 4 but missing 2, 5, 6. Adding just 2 allows you to represent all numbers 1-6! Input & Output
example_1.py β Basic Case
$
Input:
nums = [1, 3], n = 6
βΊ
Output:
1
π‘ Note:
Initially we can form {1, 3, 4}. We're missing 2, 5, 6. By adding 2, we can now form {1, 2, 3, 4, 5, 6} since 5 = 2+3 and 6 = 1+2+3. Only 1 patch needed!
example_2.py β Empty Array
$
Input:
nums = [1, 5, 10], n = 20
βΊ
Output:
2
π‘ Note:
We can form {1, 5, 6, 10, 11, 15, 16}. Missing many numbers. We need to add 2 (extends to cover 1-2), then 4 (extends to cover 1-8), then we can use existing numbers to reach 20.
example_3.py β Already Complete
$
Input:
nums = [1, 2, 2], n = 5
βΊ
Output:
0
π‘ Note:
We can already form all numbers 1-5: {1, 2, 3=1+2, 4=2+2, 5=1+2+2}. No patches needed!
Constraints
- 1 β€ n β€ 231 - 1
- 0 β€ nums.length β€ 1000
- 1 β€ nums[i] β€ n
- nums is sorted in ascending order
Visualization
Tap to expand
Understanding the Visualization
1
Start at position 1
We need to cover from 1 to n
2
Use existing segments
If we have a segment that starts at or before our current position, use it
3
Add missing segments
If there's a gap, add the optimal segment that doubles our reach
4
Extend coverage
Each addition strategically extends our coverage range
Key Takeaway
π― Key Insight: If you can represent [1, miss-1], adding 'miss' optimally extends your range to [1, 2Γmiss-1]. This greedy choice minimizes patches needed!
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code