Coin Change II - Problem
Coin Change II presents a classic dynamic programming challenge in combinatorics. You're given an array of coins representing different denominations and an integer amount representing a target sum. Your goal is to find how many different ways you can combine these coins to make exactly that amount.

Key points:
• You have an unlimited supply of each coin type
• Order doesn't matter - [1,2] and [2,1] count as the same combination
• If the amount cannot be made, return 0
• The result fits in a 32-bit integer

For example, with coins [1, 2, 5] and amount 5, there are 4 ways: [5], [2,2,1], [2,1,1,1], [1,1,1,1,1].

Input & Output

example_1.py — Basic Case
$ Input: coins = [1,2,5], amount = 5
Output: 4
💡 Note: There are 4 ways to make amount 5: [5], [2,2,1], [2,1,1,1], [1,1,1,1,1]
example_2.py — No Solution
$ Input: coins = [2], amount = 3
Output: 0
💡 Note: Amount 3 cannot be made with only coin value 2 (odd amount with even coins)
example_3.py — Zero Amount
$ Input: coins = [10], amount = 0
Output: 1
💡 Note: There is exactly one way to make amount 0: use no coins at all

Visualization

Tap to expand
Coin Change II: Making Amount 5Available coins: [1, 2, 5] - Find all unique ways4 Different Ways to Make Amount 5Way 1: Using one 5-coin5Total: 5Way 2: Two 2-coins + One 1-coin221Total: 2+2+1 = 5Way 3: One 2-coin + Three 1-coins2111Total: 2+1+1+1 = 5Way 4: Five 1-coins11111Total: 1+1+1+1+1 = 5Answer: 4 unique ways
Understanding the Visualization
1
Setup
Start with amount 5 and coins [1,2,5]
2
Find Ways
Systematically find all unique combinations
3
Count Total
Sum up all valid ways to make the target amount
Key Takeaway
🎯 Key Insight: Dynamic programming builds solutions systematically, processing one coin type at a time to avoid counting duplicate combinations like [1,2] and [2,1] separately.

Time & Space Complexity

Time Complexity
⏱️
O(n × amount)

We iterate through each coin (n) and for each coin through all amounts up to target

n
2n
Linear Growth
Space Complexity
O(amount)

Only need 1D array to store ways to make each amount from 0 to target

n
2n
Linearithmic Space

Constraints

  • 1 ≤ coins.length ≤ 300
  • 1 ≤ coins[i] ≤ 5000
  • 0 ≤ amount ≤ 5000
  • All coin values are positive integers
  • The answer is guaranteed to fit in a signed 32-bit integer
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.4K Views
High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen