Skip to content
Problem 330 · LeetCode 330(opens in a new tab)

Patching Array

HardArrays

You get a sorted list of positive whole numbers, nums, and a number n. A number can be made if some of the elements of nums, each used at most once, add up to it.

You may add new numbers to the list (each addition is a patch). Return the fewest patches so that every number from 1 to n can be made.

Example 1

Input:  nums = [1, 4], n = 10
Output: 2
Why:    add 2 and 8; then [1, 2, 4, 8] makes every sum up to 15
2 more examples and the constraints

Example 2

Input:  nums = [2, 3], n = 6
Output: 1
Why:    nothing makes 1; after adding 1, the sums 1 to 6 all work

Example 3

Input:  nums = [1, 1, 3], n = 5
Output: 0
Why:    1, 2, 3, 4 and 5 can already be made

Constraints

  • 1 ≤ length of nums ≤ 1,000
  • 1 ≤ nums[i] ≤ 10,000
  • The values of nums never go down from left to right
  • n is between 1 and 2,147,483,647 (2³¹ − 1)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Patch, then start overO(p · (m + p))
  2. One greedy passO(m + log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 numbers and n = 2³¹ − 1Verdict
Patch, then start overO(p · (m + p))
Passes; repeats the walk
One greedy passO(m + log n)
Best; one walk

m = length of nums, p = number of patches (at most about log₂ n).

Edge cases to test

  • 1 is missing. If nums[0] > 1, the first move is always to patch 1, as in Example 2.
  • n is tiny. With [1, 7, 100] and n = 3, only 2 must be added; the large numbers never matter.
  • Already complete. [1, 1, 3] with n = 5 needs 0 patches.
  • The largest n. n = 2³¹ − 1 with nums = [1] needs 30 patches: 2, 4, 8 and so on. reach must not overflow.

Common mistakes

  • Patching the missing number found by scanning sums one at a time, which takes far too long for large n.
  • Patching a number smaller than reach + 1, which grows the range less.
  • Keeping reach in a 32-bit int, so 2 · reach + 1 overflows near the top of the range.

How to talk through it

  1. 1Clarify. Is each element used at most once? Can values repeat? How large can n be?
  2. 2Track one number. reach: every sum from 1 to reach can be made. The first sum that might be missing is reach + 1.
  3. 3Grow or patch. A number up to reach + 1 extends the range by itself. If the next one is bigger, patch reach + 1, the largest useful choice.
  4. 4Give the cost. Each patch doubles reach, so O(m + log n) time and O(1) space.
  5. 5Test out loud. Run a list without 1, an already complete list, and [1] with the largest n.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?