Patching Array

HardGreedygreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a sorted array of positive integers nums and an integer n. You may add ("patch") extra positive integers into the array. After patching, every integer in the range [1, n] must be expressible as the sum of some subset of the array's elements (each element used at most once). Return the minimum number of patches required. Aim for O(len(nums) + log n) time.

Examples

Input: nums = [1,3], n = 6
Output: 1
Without patches only 1, 3, 4 are reachable. Adding 2 makes every value 1-6 reachable.
Input: nums = [1,5,10], n = 20
Output: 2
Adding 2 and 4 is one optimal choice.
Input: nums = [1,2,2], n = 5
Output: 0
Sums 1, 2, 3, 4, 5 are already reachable.

Constraints

  • 0 <= nums.length <= 1000
  • 1 <= nums[i] <= 10^4
  • `nums` is sorted in non-decreasing order
  • 1 <= n <= 2^31 - 1

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems