Algorithms · Visualized
DP: Coin Change
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Finds the minimum number of coins from given denominations needed to make up a target amount (unlike the greedy version, this works correctly for ANY set of denominations). Time: O(amount × coins) average, O(amount × coins) worst; space: O(amount) — the dp array.
Big-O: The most-asked interview category — 35 classics here.
Coin Change (Minimum Coins)
Dynamic ProgrammingFinds the minimum number of coins from given denominations needed to make up a target amount (unlike the greedy version, this works correctly for ANY set of denominations). dp[i] represents the minimum coins needed to make amount i, built by trying every coin as the 'last' coin used.
How Coin Change Works
- Define dp[i] as the minimum number of coins needed to make amount i. Base case: dp[0] = 0. Initialize all other dp values to a large 'impossible' number (like infinity).
- For each amount i from 1 to the target, try every coin denomination.
- For each coin that is less than or equal to i, consider using it as the last coin: this requires dp[i - coin] + 1 coins total.
- Set dp[i] to the minimum across all valid coin choices.
- Return dp[target]; if it's still the 'impossible' placeholder value, the target amount cannot be made with the given coins.
Coin Change Worked Example
Input: {coins: [1, 2, 5], amount: 11}
dp[0]=0. dp[1]=1(using a 1-coin). dp[2]=1(using a 2-coin). dp[3]=min(dp[2]+1,dp[1]+1)=2. dp[5]=1(a 5-coin directly). Building up to dp[11]: best is using 5+5+1 → dp[11]=3. Minimum coins needed: 3.
| 0 | |
|---|---|
| dp | 0 |
def coin_change(coins, amount):
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for c in coins:
if c <= i:
dp[i] = min(dp[i], dp[i - c] + 1)
return dp[amount] if dp[amount] <= amount else -1Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Coin Change Time & Space Complexity
When to Use Coin Change
- Making change with any currency system (including non-standard denominations where greedy fails), and general 'minimum items to reach a target sum' resource problems.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.