#330

Patching Array

Hard
ArrayGreedyGreedyArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a greedy strategy to ensure that we can form all numbers from 1 to n with the minimum number of patches. We keep track of the maximum number we can form and add patches only when necessary.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to track the maximum number that can be formed (initially 0).
  2. 2Step 2: Iterate through the numbers from 1 to n.
  3. 3Step 3: If the current number is greater than the maximum number that can be formed, add it as a patch and update the maximum number.
  4. 4Step 4: If the current number is in the array, update the maximum number that can be formed by adding this number.
solution.py14 lines
1# Full working Python code
2def min_patches(nums, n):
3    patches = 0
4    max_reachable = 0
5    i = 0
6    while max_reachable < n:
7        if i < len(nums) and nums[i] <= max_reachable + 1:
8            max_reachable += nums[i]
9            i += 1
10        else:
11            patches += 1
12            max_reachable += (max_reachable + 1)
13    return patches
14

Complexity note: The complexity is O(n) because we iterate through the array and the numbers we need to cover, ensuring we only make necessary patches.

  • 1Using a greedy approach minimizes the number of patches by always extending the range of reachable sums.
  • 2The maximum number that can be formed at any point is crucial for determining whether a patch is needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.