Coin Change dynamic programming algorithm explained step-by-step: unbounded knapsack formulation, bottom-up 1D DP table, greedy failure counterexamples, and JavaScript implementation.
Given an array of distinct coin denominations and a target amount of money, the Coin Change Problem asks for the fewest number of coins required to make up that exact amount. You may assume an infinite supply of each coin denomination.
A simple greedy heuristic (always picking the largest denomination) fails on arbitrary currency systems (for example, with coins [1, 3, 4] and target 6, greedy picks 4 + 1 + 1 = 3 coins, whereas the optimal DP solution is 3 + 3 = 2 coins). Dynamic Programming guarantees global optimality in O(N · amount) time and O(amount) space.
Create an array `dp` of size `amount + 1` filled with `Infinity`. Set base case `dp[0] = 0` (zero coins are needed to make an amount of 0).
Iterate through each sub-amount `i` from 1 up to `amount`.
For each coin denomination where `coin <= i`, calculate `dp[i] = Math.min(dp[i], 1 + dp[i - coin])`. This models the decision to use the current coin plus the optimal solution for the remainder.
If `dp[amount]` remains `Infinity` after checking all coins, the target amount cannot be composed by any combination of the provided coins; return -1.
1function coinChange(coins, amount) {2 // dp[i] stores the minimum number of coins needed for sub-amount i3 const dp = new Array(amount + 1).fill(Infinity);4 dp[0] = 0; // Base case: 0 coins needed for amount 05 6 // Build DP table from 1 to amount7 for (let i = 1; i <= amount; i++) {8 for (const coin of coins) {9 if (i - coin >= 0 && dp[i - coin] !== Infinity) {10 dp[i] = Math.min(dp[i], 1 + dp[i - coin]);11 }12 }13 }14 15 return dp[amount] === Infinity ? -1 : dp[amount];16}17 18// Example usage:19// coinChange([1, 2, 5], 11); // 3 (5 + 5 + 1)20// coinChange([2], 3); // -1 (Impossible)21// coinChange([1, 3, 4], 6); // 2 (3 + 3, beats greedy 4 + 1 + 1)Play through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Overlapping subproblem memoization & DP table animator
Test your understanding of Coin Change Problem complexity and step mechanics.
Q1.Why does a greedy choice (always picking the largest coin) fail for general coin systems?
Q2.What is the time complexity of the bottom-up DP Coin Change algorithm?
Apply Coin Change Problem to real coding interview questions.
Find the minimum number of coins needed to make up a given amount.
Return the number of distinct combinations that make up the target amount.