#2952

Minimum Number of Coins to be Added

Medium
ArrayGreedySortingGreedySorting
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(1)

The optimal approach uses a greedy strategy to determine the smallest unobtainable integer and adds coins as needed to cover the range up to the target. This is efficient because it systematically builds the range of obtainable sums without unnecessary computations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the coins array.
  2. 2Step 2: Initialize a variable to track the smallest unobtainable sum, starting at 1.
  3. 3Step 3: Iterate through the sorted coins, checking if the current coin can cover the smallest unobtainable sum.
  4. 4Step 4: If the current coin is greater than the smallest unobtainable sum, add coins to cover the gap.
  5. 5Step 5: Continue until all integers up to the target are obtainable.
solution.py16 lines
1# Full working Python code
2
3def min_coins_to_add(coins, target):
4    coins.sort()
5    missing_count = 0
6    smallest_unobtainable = 1
7    for coin in coins:
8        while coin > smallest_unobtainable:
9            missing_count += 1
10            smallest_unobtainable *= 2
11        smallest_unobtainable += coin
12    while smallest_unobtainable <= target:
13        missing_count += 1
14        smallest_unobtainable *= 2
15    return missing_count
16

Complexity note: The sorting step dominates the complexity, making it O(n log n), while the subsequent iterations are linear.

  • 1Understanding how to build up obtainable sums helps in optimizing the solution.
  • 2Using a greedy approach allows us to minimize the number of coins needed efficiently.

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