Patching Array — LeetCode 330 Python Solution

HardGreedyArray
Problem
#330
Pattern
Greedy
Reading time
2 min

The problem

Given a sorted integer array nums and an integer n, 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.

Example

Input
nums = [1,3], n = 6
Output
1
Explanation
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.

Python solution

Python
class Solution:
    def minPatches(self, nums: List[int], n: int) -> int:
        x = 1
        ans = i = 0
        while x <= n:
            if i < len(nums) and nums[i] <= x:
                x += nums[i]
                i += 1
            else:
                ans += 1
                x <<= 1
        return ans

Complexity

MeasureComplexity
TimeO(m + \log n), where m is the length of the array nums
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 330. Patching Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 330. Patching Array?
LeetCode 330. Patching Array is rated Hard on LeetCode.
What is the time complexity of LeetCode 330. Patching Array?
The Python solution on this page runs in O(m + \log n), where m is the length of the array nums.
What is the space complexity of LeetCode 330. Patching Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 330. Patching Array cover?
LeetCode 330. Patching Array is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview