Program to find number of combinations of coins to reach target in Python

Suppose we have a list of coins and another value amount, we have to find the number of combinations there are that sum to amount. If the answer is very large, then mod the result by 10^9 + 7.

So, if the input is like coins = [2, 5] amount = 10, then the output will be 2, as we can make these combinations − [2, 2, 2, 2, 2], [5, 5]

Algorithm

To solve this, we will follow these steps −

  • m := 10^9 + 7
  • dp := a list of size same as amount + 1, and fill it with 0
  • dp[0] := 1
  • for each d in coins, do
    • for i in range 1 to size of dp, do
      • if i - d >= 0, then
        • dp[i] := dp[i] + dp[i - d]
  • return (last element of dp) mod m

Example

Let us see the following implementation to get better understanding −

class Solution:
    def solve(self, coins, amount):
        dp = [0] * (amount + 1)
        dp[0] = 1
        for d in coins:
            for i in range(1, len(dp)):
                if i - d >= 0:
                    dp[i] += dp[i - d]
        return dp[-1] % (10 ** 9 + 7)

ob = Solution()
coins = [2, 5]
amount = 10
print(ob.solve(coins, amount))

The output of the above code is −

2

How It Works

The algorithm uses dynamic programming where dp[i] represents the number of ways to make amount i. We iterate through each coin and update all possible amounts that can be formed using that coin.

Step-by-Step Execution

def solve_with_steps(coins, amount):
    dp = [0] * (amount + 1)
    dp[0] = 1
    print(f"Initial dp: {dp}")
    
    for coin in coins:
        print(f"\nProcessing coin {coin}:")
        for i in range(1, len(dp)):
            if i - coin >= 0:
                old_value = dp[i]
                dp[i] += dp[i - coin]
                print(f"  dp[{i}] = {old_value} + dp[{i - coin}] = {dp[i]}")
        print(f"After coin {coin}: {dp}")
    
    return dp[-1] % (10 ** 9 + 7)

coins = [2, 5]
amount = 10
result = solve_with_steps(coins, amount)
print(f"\nFinal result: {result}")
Initial dp: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Processing coin 2:
  dp[2] = 0 + dp[0] = 1
  dp[4] = 0 + dp[2] = 1
  dp[6] = 0 + dp[4] = 1
  dp[8] = 0 + dp[6] = 1
  dp[10] = 0 + dp[8] = 1
After coin 2: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

Processing coin 5:
  dp[5] = 0 + dp[0] = 1
  dp[7] = 0 + dp[2] = 1
  dp[9] = 0 + dp[4] = 1
  dp[10] = 1 + dp[5] = 2
After coin 5: [1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 2]

Final result: 2

Conclusion

This dynamic programming solution efficiently finds the number of coin combinations by building up solutions for smaller amounts. The time complexity is O(amount × number of coins) and space complexity is O(amount).

Updated on: 2026-03-25T12:38:49+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements