Coin Change (LeetCode 322): Solution and Explanation

Medium
Array
Dynamic Programming
Breadth First Search

You have unlimited coins of several denominations and a target amount. Return the smallest number of coins that add up exactly to the amount, or -1 if the amount cannot be formed.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The tempting first idea is greedy: keep taking the largest coin that fits. It works for everyday currency but fails in general. With coins 1, 3 and 4 and amount 6, greedy takes 4, 1, 1 for three coins, while 3 plus 3 needs only two. Trying every combination recursively fixes correctness but explodes, because the same remaining amount appears down many different branches.

The structure that saves us is optimal substructure. If the best way to make amount a uses coin c last, then the rest of it must be the best way to make a - c. So the fewest coins for a is one plus the minimum, over every coin that fits, of the fewest coins for a - c. Each smaller amount only needs to be solved once.

Build the answers from 0 upward. dp[0] = 0 because zero coins make zero. Every other entry starts at amount + 1, a value that can never be a real answer since even all ones would use only amount coins. That sentinel acts as infinity without any special overflow handling, and if dp[amount] still holds it at the end, the amount is unreachable.

Approach: Bottom-up DP over amounts

  1. Create dp of size amount + 1 filled with amount + 1 as an impossible sentinel.
  2. Set dp[0] = 0.
  3. For each amount a from 1 to amount, loop over every coin c.
  4. If a - c >= 0, update dp[a] = min(dp[a], 1 + dp[a - c]).
  5. After the loops, return dp[amount] if it is not the sentinel, otherwise -1.

Step-by-step example

coins = [1,3,4], amount = 6
  1. Start with dp = [0, 7, 7, 7, 7, 7, 7].
  2. a = 1: only coin 1 fits, dp[1] = 1. a = 2: dp[2] = 1 + dp[1] = 2.
  3. a = 3: coin 1 gives 3, coin 3 gives 1 + dp[0] = 1, so dp[3] = 1.
  4. a = 4: coin 1 gives 2, coin 3 gives 2, coin 4 gives 1, so dp[4] = 1.
  5. a = 5: coin 1 gives 1 + dp[4] = 2, coin 3 gives 3, coin 4 gives 2, so dp[5] = 2.
  6. a = 6: coin 1 gives 3, coin 3 gives 1 + dp[3] = 2, coin 4 gives 1 + dp[2] = 3, so dp[6] = 2. Return 2.

Code: Python, Java, C++

1class Solution:
2    def coinChange(self, coins: List[int], amount: int) -> int:
3        dp = [amount + 1] * (amount + 1)
4        dp[0] = 0
5        
6        for a in range(1, amount + 1):
7            for c in coins:
8                if a - c >= 0:
9                    dp[a] = min(dp[a], 1 + dp[a - c])
10                    
11        return dp[amount] if dp[amount] != amount + 1 else -1

Time and space complexity

Time

O(amount × k)

For each of the amount values the inner loop checks all k coin denominations, doing constant work per pair.

Space

O(amount)

The dp array stores one entry for every value from 0 to amount.

Other approaches

BFS over remaining amounts (time O(amount × k), space O(amount))

Treat each amount as a node and each coin as an edge that subtracts its value. A BFS from amount reaches 0 in the fewest steps, which is the fewest coins. It can stop early once 0 is found, but needs a visited set.

Top-down recursion with memoization (time O(amount × k), space O(amount))

Recursively compute the fewest coins for a as one plus the best result for a - c, caching each amount. It is equivalent to the table but may recurse up to amount levels deep.

Common mistakes

  • Using a greedy largest-coin-first strategy, which fails on coin sets like [1,3,4].
  • Initializing the table with a language's max integer and then computing 1 + dp[a - c], which overflows in Java or C++. The amount + 1 sentinel avoids this.
  • Forgetting that amount 0 should return 0, not -1.
  • Confusing this with the counting version of the problem, which needs the coin loop outside the amount loop to avoid counting permutations.

Frequently asked questions

Why doesn't a greedy algorithm work for coin change?

Greedy only works for special coin systems. With coins 1, 3 and 4 and amount 6, taking the largest coin first gives 4, 1, 1, while the optimum is 3, 3. Dynamic programming considers every last coin choice, so it always finds the minimum.

Why initialize the DP array with amount + 1?

No valid answer can exceed amount coins, because even using only 1s takes exactly amount coins. So amount + 1 works as infinity, and adding 1 to it never overflows.

What is the time complexity of coin change?

It is O(amount × k), where k is the number of coin denominations, because each amount checks every coin once. Space is O(amount) for the table.

Does the order of the two loops matter for coin change?

For the minimum number of coins it does not, because the minimum over combinations equals the minimum over orderings. Looping amounts outside and coins inside, as here, or the reverse both give the right answer. Order matters only when you count the number of ways, where coins must be the outer loop to avoid counting the same multiset several times.