Patching Array - Problem
You're given a sorted integer array 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
Bridge Building Analogy: Patching ArrayRiver (Range 1 to n=6)01234567Available Bridge Segments: nums = [1, 3]Segment 1Segment 3Problem: Gap between positions 1 and 3!Missing: 2Need bridge here!Solution: Add optimal segment (patch = 2)1 (given)2 (patch)3 (given)Coverage Analysis:With segments {1, 2, 3}, we can build complete bridge:1 = [1], 2 = [2], 3 = [3], 4 = [1,3], 5 = [2,3], 6 = [1,2,3]Answer: 1 patch
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!
Asked in
Google 45 Amazon 38 Facebook 28 Microsoft 22
42.0K Views
Medium Frequency
~25 min Avg. Time
1.5K 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