Taro Logo

Coin Change

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+32
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2K views
Topics:
Dynamic Programming

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Example 1:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Example 3:

Input: coins = [1], amount = 0
Output: 0

Constraints:

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 231 - 1
  • 0 <= amount <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the coin denominations include zero or negative numbers?
  2. Are the coin denominations guaranteed to be unique, or could there be duplicates in the input array?
  3. What is the maximum value of the target amount and the maximum length of the coin denominations array?
  4. If the target amount is zero, what should be the expected return value?
  5. Is it possible that no combination of coins can make up the target amount, and if so, should I strictly return negative one?

Brute Force Solution

Approach

Imagine you have a target amount of money to make and a collection of various coin values, and you want to find the fewest coins needed to reach that exact amount. The brute force strategy works by exhaustively testing every single combination of coins to see which ones add up to the target and then picking the combination that uses the fewest coins.

Here's how the algorithm would work step-by-step:

  1. Start with your target amount of money and all the available coin values.
  2. Pick one coin from your collection and subtract its value from your current amount.
  3. If the remaining amount is zero, you have successfully made the target amount using that specific group of coins, so count how many coins you used.
  4. If the remaining amount is greater than zero, repeat the process by picking another coin from your collection and subtracting its value.
  5. If the remaining amount drops below zero, it means you went past your target, so abandon that particular combination and backtrack.
  6. Explore every possible path of picking coins until you have tested every single combination that adds up to the target amount.
  7. Compare the valid combinations you found and select the one that required the fewest total coins to reach the goal.

Code Implementation

def coin_change_brute_force(coin_values, target_amount):
    # We define a recursive helper to explore every combination of coin subtractions
    def recursive_explore(remaining_amount):
        if remaining_amount == 0:
            return 0
        
        if remaining_amount < 0:
            return float('inf')
        
        minimum_coins_needed = float('inf')
        for current_coin in coin_values:
            result_from_subpath = recursive_explore(remaining_amount - current_coin)
            if result_from_subpath != float('inf'):
                minimum_coins_needed = min(minimum_coins_needed, result_from_subpath + 1)
                
        return minimum_coins_needed

    # We initiate the search from the full target amount down to zero
    total_coins_result = recursive_explore(target_amount)
    
    if total_coins_result == float('inf'):
        return -1
    
    return total_coins_result

Big(O) Analysis

Time Complexity
O(S^c) – In this brute force strategy, we recursively explore every possible combination of coin values until we reach or exceed the target amount S. If we let c represent the number of different coin denominations available, each step of the recursion branches out into c possibilities. We continue branching and subtracting until we reach the target or a negative amount, leading to a decision tree of depth up to S. This results in approximately c^S operations, which simplifies to the exponential time complexity of O(S^c).
Space Complexity
O(amount) – The space complexity is driven by the dynamic programming table or the recursive call stack needed to store the minimum coin counts for every sub-amount from zero up to the target. In this analysis, we define N as the target amount of money we want to make. This requires an auxiliary array or stack frames proportional to N in size, resulting in a linear space complexity relative to the target amount.

Optimal Solution

Approach

Instead of blindly guessing every combination of coins, the optimal strategy builds the solution from the ground up, starting with the smallest target amount. It figures out the minimum coins needed for every smaller target first, using those answers to easily solve for the final goal.

Here's how the algorithm would work step-by-step:

  1. Start by figuring out how to make zero money, which requires zero coins.
  2. Move to the next target amount and check which coin values you have available to reach this amount.
  3. For the current target amount, pretend you are using each available coin one at a time, and look back at the answer you already figured out for the remaining money left over.
  4. Add the current coin to that past answer to see how many total coins you would need.
  5. Compare the results from all available coins and pick the smallest total.
  6. Save this best answer for the current target amount so you can use it for larger amounts later.
  7. Repeat this process step by step for every target amount until you reach your ultimate goal, ensuring you never have to recalculate anything from scratch.

Code Implementation

def coin_change(coin_denominations, target_amount):
    # We initialize with target_amount + 1 as an infinity placeholder to safely find minimums.
    minimum_coins_table = [target_amount + 1] * (target_amount + 1)
    
    minimum_coins_table[0] = 0

    # We build solutions from the ground up to prevent redundant calculations.
    for current_amount in range(1, target_amount + 1):
        for coin_value in coin_denominations:
            if current_amount >= coin_value:
                # We look back at subproblems to find the optimal substructure for this amount.
                previous_amount = current_amount - coin_value
                potential_answer = minimum_coins_table[previous_amount] + 1
                minimum_coins_table[current_amount] = min(minimum_coins_table[current_amount], potential_answer)

    if minimum_coins_table[target_amount] > target_amount:
        return -1

    return minimum_coins_table[target_amount]

Big(O) Analysis

Time Complexity
O(amount * n) – To solve the coin change problem, we use a bottom-up approach with nested loops where the outer loop iterates through every target amount from 1 up to the target amount (representing our amount size), and the inner loop iterates through each of the n available coin denominations. For each target amount, we perform a constant number of operations by checking every coin to find the minimum. This results in approximately amount * n total operations, which simplifies to the Big O time complexity of O(amount * n).
Space Complexity
O(target) – The algorithm allocates an auxiliary dp array of size target plus one to store the minimum number of coins needed for every intermediate amount from zero up to the final goal. As the target amount increases, this DP table grows linearly to hold the results of all previously solved subproblems. Therefore, the extra memory used scales directly with the size of the target rather than the number of coin denominations. Simplifying this linear relationship yields a total auxiliary space complexity of O(target).

Edge Cases

Target amount is zero
How to Handle:
Return zero immediately since zero coins are needed to make a total of zero.
No valid combination of coins can form the target amount
How to Handle:
Return negative one as specified by the problem constraints when the target is unreachable.
Coins array contains values larger than the target amount
How to Handle:
Ignore any coin whose denomination exceeds the remaining target during the state transition checks.
Coins array includes zero as a denomination
How to Handle:
Skip zero values during initialization or processing to prevent infinite loops and division by zero errors.
Coins array contains negative numbers
How to Handle:
Filter out negative coin values at the start since denominations must be positive.
Very large target amount causing integer overflow during addition
How to Handle:
Use infinity or a value larger than the max possible coin count to represent unreachable states safely.
Single coin denomination equal to the target amount
How to Handle:
Return one since the exact target can be made using a single coin of that value.
Maximum-sized inputs with deep target values
How to Handle:
Use bottom-up dynamic programming with a linear array to ensure efficient scaling and prevent stack overflow.
0/75 completed