Taro Logo

Coin Change II

#70 Most AskedMedium
0 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 number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

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

The answer is guaranteed to fit into a signed 32-bit integer.

Example 1:

Input: amount = 5, coins = [1,2,5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1

Example 2:

Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.

Example 3:

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

Constraints:

  • 1 <= coins.length <= 300
  • 1 <= coins[i] <= 5000
  • All the values of coins are unique.
  • 0 <= amount <= 5000

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. What are the constraints on the target amount and the values within the coin denominations array?
  2. Can the coin denominations array contain duplicate values, and if so, should they be ignored or treated as distinct coins?
  3. What should be returned if the target amount is zero? Is it considered that there is one way to make zero (by using no coins), or should it return zero?
  4. What should be returned if the target amount cannot be made up by any combination of the given coins?
  5. Can we assume the coin denominations are strictly positive integers (i.e., no zeros or negative values)?

Brute Force Solution

Approach

Imagine you have a target amount of money and a collection of coin values, and you want to find every possible combination of those coins that adds up to the exact target. The brute force approach explores every single combination of coins possible to see which ones successfully reach the target amount.

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

  1. Start by looking at the available coin values.
  2. Begin making piles of coins by repeatedly picking different coins from your collection.
  3. Keep adding coins to your current pile until the total value either equals your target or goes past it.
  4. If the total value in your pile matches your target exactly, count this as a successful way to make the change.
  5. If the total value goes past your target, stop exploring that specific pile because it has failed.
  6. If the total is still less than your target, keep adding more coins in every possible combination.
  7. Repeat this exhaustive exploration for every possible starting coin and every combination that follows until every path has been tested.
  8. Finally, count up all the successful piles you found that reached the exact target value.

Code Implementation

class Solution:
    def change(self, target_amount: int, coin_values: list[int]) -> int:
        
        # We use a recursive helper function to explore every possible coin combination path.
        def explore_combinations(current_index, remaining_target):
            if remaining_target == 0:
                return 1
            
            if remaining_target < 0 or current_index == len(coin_values):
                return 0
            
            include_current_coin = explore_combinations(current_index, remaining_target - coin_values[current_index])
            
            exclude_current_coin = explore_combinations(current_index + 1, remaining_target)
            
            return include_current_coin + exclude_current_coin

        return explore_combinations(0, target_amount)

Big(O) Analysis

Time Complexity
O(S * n) – The time complexity is driven by exploring combinations of coins for every possible sub-amount up to the target. For a target amount S and n coin denominations, the algorithm iterates through each coin and updates the number of ways to form every amount from that coin's value up to S. This results in approximately S * n total operations, which simplifies to O(S * n).
Space Complexity
O(target) – To keep track of the successful ways to make change during the exhaustive exploration of coin piles, we use an auxiliary one-dimensional array of size target plus one. Each index in this array stores the number of valid combinations to reach that specific sub-amount up to the final target. As the target amount grows, the memory required for this lookup table scales linearly with the target value. Therefore, the auxiliary space complexity is determined by the size of the target amount rather than the number of available coin values.

Optimal Solution

Approach

Instead of exploring every possible combination of coins at once, the optimal approach builds up the solution gradually by tackling one coin type at a time. By accumulating the number of ways to reach every target amount step by step, we avoid repeating work and efficiently find the total number of combinations.

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

  1. Begin with a starting target amount of money and assume there is initially only one way to make zero money, which is by using no coins at all.
  2. Take the smallest coin available and figure out how many ways it can help you build every target amount up to your final goal.
  3. Record these new possibilities so you know how many different combinations exist for each specific amount using just this first coin.
  4. Bring in the next coin size and update your running totals by combining the new possibilities it creates with the possibilities you already figured out for the previous coins.
  5. Continue this process for each remaining coin in your collection, always updating your running totals to include the influence of the newest coin.
  6. Once you have processed every coin, look at your final tally for your ultimate target amount to see the total number of possible combinations.

Code Implementation

def change(target_amount, coin_denominations):
    # Initialize table to store ways to form each amount, starting with zero amount.
    ways_to_reach_amount = [0] * (target_amount + 1)
    ways_to_reach_amount[0] = 1

    # Process each coin independently to build combinations iteratively.
    for current_coin in coin_denominations:
        for running_amount in range(current_coin, target_amount + 1):
            # Accumulate combinations by adding the ways to form the remainder amount.
            ways_to_reach_amount[running_amount] += ways_to_reach_amount[running_amount - current_coin]

    return ways_to_reach_amount[target_amount]

Big(O) Analysis

Time Complexity
O(amount * n) – To analyze the time complexity, we examine the two main dimensions driving the cost: the target amount and the number of available coin denominations represented by n. For each individual coin, we iterate through every integer value from that coin's value up to the final target amount to update the combination counts. This means we perform a constant amount of work inside a nested structure where the outer loop runs n times for the coins and the inner loop runs amount times. This leads to approximately n * amount operations, which simplifies to the final Big O time complexity of O(amount * n).
Space Complexity
O(amount) – To implement the gradual building of solutions described in the steps, we utilize a single one-dimensional auxiliary array of size equal to the target amount plus one. This array keeps track of the running totals of combinations for every intermediate amount from zero up to the final goal. The space required for this array depends entirely on the target amount, which we define as our input size N. Therefore, the extra memory scales linearly with N, while the collection of coins itself only dictates the number of iterations rather than increasing the auxiliary storage.

Edge Cases

Target amount is zero
How to Handle:
Return one because there is exactly one way to make zero amount by using no coins.
Coin denominations are larger than the target amount
How to Handle:
The dynamic programming table will correctly retain a count of zero for the target since no combination can be formed.
Empty coins array with a positive target amount
How to Handle:
Return zero immediately because no coins are available to form the target.
Coins array contains duplicate denominations
How to Handle:
The nested iteration processes each coin value independently, so duplicates naturally contribute properly without causing overcounting.
Maximum target amount and large coin arrays
How to Handle:
Use a 1D dynamic programming array with 64-bit integers to prevent integer overflow and ensure efficient scaling.
Coins array contains a zero denomination
How to Handle:
Filter out zero values or handle them carefully to prevent infinite loops in coin selection logic.
Coins array contains negative numbers
How to Handle:
Pre-screen and ignore negative denominations because coin values must be strictly positive to avoid infinite combinations.
Single coin denomination that exactly divides the target
How to Handle:
The algorithm will increment the combination count at the target index exactly once when that single coin is repeatedly applied.
0/257 completed