15% off all plans & roadmaps Use code

See plans

Coin Change

Updated

TL;DR: Find the fewest coins that sum to a target amount, or -1 if impossible. Build answers for every amount from 0 up to the target, since each amount needs only the answers for smaller amounts.

Problem

You are given an integer array coins holding coin denominations and an integer amount holding a target sum of money.

Return the fewest coins needed to make exactly that amount. If no combination of the coins can make the amount, return -1. You have an unlimited supply of each coin.

Example 1

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2

Input: coins = [2], amount = 3
Output: -1

Example 3

Input: coins = [1], amount = 0
Output: 0

Constraints

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4

Constraints that matter

  • amount is at most 10^4, so a table with one cell per amount is tiny. An O(amount * coins) solution does at most 120,000 steps.
  • coins.length is at most 12, so the inner loop over coins is a small constant factor. Plain recursion still blows up because its branching compounds with depth.
  • coins[i] can reach 2^31 - 1. Any coin larger than the current amount is useless, and computing i - coin for such a coin must not index the array out of range.
  • amount can be 0, and the answer is then 0 coins. The base case has to cover this without special handling.
  • Coin values are arbitrary, so no divisibility structure exists. This rules out greedy and forces you to compare every coin at every amount.

View on LeetCode

Hints

Hint 1

This is a minimum-cost question over a sum, and the sum is small.

Hint 2

Define solve(rem) as the fewest coins for the remaining amount rem.

Solution

Intuition

This is a minimum-cost question over a sum, and the sum is small. That points to Dynamic Programming on a 1D array. The state is a single number, the remaining amount, so there are at most 10^4 + 1 distinct subproblems.

Picture a row of numbered mailboxes, one for each amount from 0 to the target. Each box holds the fewest coins needed to reach that amount, and you fill them left to right so every box you need is already written when you get to it.

Look at the last coin in an optimal answer for amount a. Whatever coin c it is, the coins before it form an optimal answer for a - c. If they were not optimal, you could swap in a better set and improve the answer for a. So the best answer for a is 1 plus the best answer among a - c over all coins c.

A direct recursion on that rule recomputes the same amounts many times. Amount 2 is reached from 7 by a 5-coin, from 6 by a 4-coin, from 5 by a 3-coin, and so on. Caching each amount's answer turns the exponential tree into at most amount distinct calls. Filling the cache from small amounts to large removes the recursion entirely.

Greedy does not work here. With coins 1, 3, 4 and amount 6, taking the biggest coin gives 4 + 1 + 1, which is three coins. The best is 3 + 3, which is two. Only trying every coin at every amount is safe.

Watch the pattern animation

Worked example

Input: coins = [1, 3, 4, 5], amount = 7
Output: 2
Explanation: The best split is 3 + 4, which uses two coins. Using 5 leaves 2, which needs two more 1-coins, so that path costs 3. Using the largest coin first does not win here, which is why a greedy pick is unsafe.

Approach 1: Brute force recursion

Define solve(rem) as the fewest coins for the remaining amount rem. Try every coin as the next one, recurse on rem - coin, and keep the smallest result plus one. Return -1 from a branch that cannot finish.

This tries every ordered sequence of coins whose sum does not overshoot. It is correct because it enumerates every possible answer. It is slow for the reason covered next.

Steps

  1. If rem is 0, return 0. If rem is negative, return -1 because the coin overshot.
  2. Set best to -1, meaning no solution found yet.
  3. For each coin, call solve(rem - coin).
  4. If that result is not -1 and result + 1 beats best, update best.
  5. Return best after trying all coins.
  6. Call solve(amount) and return its value.

Dry run

Take coins [1, 3, 4, 5] and amount 7. solve(7) branches into solve(6), solve(4), solve(3) and solve(2).

  • solve(4) finds the 4-coin and returns 1, so the 3-coin branch gives 2.
  • solve(3) finds the 3-coin and returns 1, so the 4-coin branch gives 2.
  • solve(6) returns 2 (for example 1 + 5), so the 1-coin branch gives 3.
  • solve(2) returns 2 (1 + 1), so the 5-coin branch gives 3.

The minimum is 2, which matches the expected output. Note that solve(1) and solve(2) run again inside the other branches. Each repeat redoes its whole subtree.

Complexity

TimeO(n^amount) worst case
SpaceO(amount)

Here n is the number of coins and amount is the target. The recursion goes at most amount levels deep, because the smallest coin is at least 1, and every call branches n ways. That gives at most n^amount calls. The only memory is the call stack, which holds at most amount frames.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        def solve(rem: int) -> int:
            if rem == 0:
                return 0
            if rem < 0:
                return -1
            best = -1
            for c in coins:
                r = solve(rem - c)
                if r >= 0 and (best < 0 or r + 1 < best):
                    best = r + 1
            return best

        return solve(amount)

Approach 2: Top-down memoization

What's slow: the recursion answers the same question, such as the best for amount 2, again and again from different branches. Each repeat expands a full subtree. The answer for a given rem never changes, so the repeated work is pure waste.

The insight that fixes it: store each answer the first time you compute it. Keep a memo array indexed by remaining amount. A cached value, including -1 for impossible, is returned immediately. Only amount distinct values of rem exist, so each is expanded once.

Steps

  1. Create memo of size amount + 1, filled with a marker (-2) meaning not computed yet.
  2. In solve(rem), return 0 for rem == 0 and -1 for rem < 0.
  3. If memo[rem] is not the marker, return it.
  4. Loop over the coins, recurse on rem - coin, and track the smallest result + 1 among valid results.
  5. Store best in memo[rem], using -1 when nothing worked.
  6. Return solve(amount).

Dry run

Use coins [1, 3, 4, 5] and amount 7. The first descent goes through the 1-coin each time, so the call chain is 7, 6, 5, 4, 3, 2, 1, 0. On the way back up, the memo fills with memo[1]=1, memo[2]=2, memo[3]=1, memo[4]=1, memo[5]=1, memo[6]=2.

No amount below 7 is recomputed after that. When solve(7) tries the 3-coin it reads memo[4]=1 at once. The 4-coin reads memo[3]=1, and the 5-coin reads memo[2]=2. The candidates for 7 are 3, 2, 2 and 3, so memo[7]=2, which is the expected output.

Complexity

TimeO(amount * n)
SpaceO(amount)

Here n is the number of coins. There are amount + 1 distinct values of rem, and each is computed once and does n units of work in its loop. Cached lookups cost O(1). The memo holds amount + 1 integers, and the recursion stack is at most amount deep, so space is O(amount).

PythonTested in our runner

import sys
from typing import List, Optional

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        # Depth can reach amount when a 1-coin exists.
        sys.setrecursionlimit(max(sys.getrecursionlimit(), 30000))
        memo = [-2] * (amount + 1)  # -2 means not computed yet

        def solve(rem: int) -> int:
            if rem == 0:
                return 0
            if rem < 0:
                return -1
            if memo[rem] != -2:
                return memo[rem]
            best = -1
            for c in coins:
                r = solve(rem - c)
                if r >= 0 and (best < 0 or r + 1 < best):
                    best = r + 1
            memo[rem] = best
            return best

        return solve(amount)
1D Array (Coin Change / Unbounded Knapsack Style) pattern infographic for Coin Change

Solution pattern

1D Array (Coin Change / Unbounded Knapsack Style)

Part of Dynamic Programming (DP) Patterns

Approach 3: Bottom-up DP tableOptimal1D Array (Coin Change / Unbounded Knapsack Style)

What's slow: memoization has the right operation count, but it pays for recursion. The call stack can grow to amount frames, and some runtimes overflow at 10^4 levels. Every call also carries function-call overhead.

The insight that fixes it: every dependency points to a smaller amount. So fill a table dp in increasing order, and each cell finds its inputs already done. dp[i] is the fewest coins for amount i. Start with dp[0] = 0 and everything else at amount + 1, a value no real answer can reach because amount 1-coins is the worst case. At the end, a cell still holding amount + 1 means impossible.

Why it is correct. Let dp[i] be the fewest coins for amount i, and assume every smaller amount is already correct. The last coin in any best answer for i must be some coin c, and the other coins must be a best answer for i - c. So dp[i] = 1 + min(dp[i - c]) over coins c that fit. Trying every coin means no candidate is skipped, so the minimum is never missed.

Steps

  1. Create dp of size amount + 1, filled with amount + 1.
  2. Set dp[0] = 0.
  3. For each amount i from 1 to amount, loop over every coin.
  4. Skip a coin when coin > i, since it cannot be used.
  5. Otherwise set dp[i] = min(dp[i], dp[i - coin] + 1).
  6. After the loops, return -1 if dp[amount] > amount, else return dp[amount].

Dry run

Coins [1, 3, 4, 5], amount 7. The table starts as [0, 8, 8, 8, 8, 8, 8, 8], using 8 as the sentinel. Each row shows the candidates dp[i - coin] + 1 for the coins that fit.

icandidates from coins 1, 3, 4, 5dp[i]
11: dp[0]+1 = 11
21: dp[1]+1 = 22
31: 3, 3: dp[0]+1 = 11
41: 2, 3: dp[1]+1 = 2, 4: dp[0]+1 = 11
51: 2, 3: dp[2]+1 = 3, 4: dp[1]+1 = 2, 5: dp[0]+1 = 11
61: 2, 3: dp[3]+1 = 2, 4: dp[2]+1 = 3, 5: dp[1]+1 = 22
71: 3, 3: dp[4]+1 = 2, 4: dp[3]+1 = 2, 5: dp[2]+1 = 32

The final table is [0, 1, 2, 1, 1, 1, 2, 2]. dp[7] = 2 is not greater than 7, so the function returns 2.

Complexity

TimeO(amount * n)
SpaceO(amount)

Here n is the number of coins. The outer loop runs amount times and the inner loop runs n times, so the work is amount * n, at most 120,000 steps under the constraints. Each step is one comparison and one addition. The only extra memory is dp, which has amount + 1 cells.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        # amount + 1 is larger than any real answer, so it acts as infinity.
        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 -1 if dp[amount] > amount else dp[amount]

Common mistakes

  • Taking the largest coin first, as in while amount > 0: take max coin <= amount. This fails on coins [1, 3, 4] with amount 6, where it returns 3 instead of 2. Try every coin at every amount and keep the minimum.
  • Filling dp with Integer.MAX_VALUE or INT_MAX and then computing dp[i - coin] + 1. The addition overflows to a negative number and wins the min. Use amount + 1 as the sentinel, or check for the sentinel before adding.
  • Forgetting the guard if coin <= i and indexing dp[i - coin] directly. A negative index is a bug in Java and C++, and in Python it silently reads from the end of the list. Coins can be as large as 2^31 - 1, so this triggers often.
  • Returning dp[amount] without the final check. An unreachable amount then returns the sentinel, such as 4 for amount 3 with coins [2]. Compare against amount + 1 and return -1.
  • Using recursion with no cache, or caching only successful answers. Without caching the work is exponential. If impossible results are not stored, the same dead branches are re-explored. Store -1 in the memo too.
  • Setting dp[0] wrong, for example to 1 or leaving it at the sentinel. Every answer is built on dp[0] = 0, so a wrong base shifts or breaks every cell. Amount 0 must return 0 coins.

Edge cases

  • coins = [1], amount = 0 returns 0, because no coins are needed for a zero target.
  • coins = [2], amount = 3 returns -1, because odd totals cannot be made from 2-coins.
  • coins = [5, 10], amount = 3 returns -1, because every coin is larger than the amount. The guard coin <= i must skip them all.
  • coins = [1], amount = 10000 returns 10000. This is the maximum depth case for recursion and the largest answer for the table.
  • coins = [2147483647], amount = 5 returns -1. A huge coin must not cause overflow or an out-of-range index.
  • coins = [186, 419, 83, 408], amount = 6249 returns 20. This case has no pattern a greedy rule can use, and DP handles it.
  • Duplicate-looking or unsorted coins, such as [5, 1, 2], give the same answer as sorted input. The solution never depends on coin order.

Follow-ups interviewers ask

How do you return the actual coins used, not only the count?
Keep a second array choice where choice[i] records the coin that gave dp[i] its best value. After filling the table, start at amount and repeat: add choice[i] to the result and move to i - choice[i] until you reach 0. This costs O(amount) extra space and O(answer length) extra time.
Can breadth-first search solve it, and how does it compare?
Yes. Treat each amount from 0 to amount as a node, with an edge from a to a + coin. The shortest path from 0 to amount is the answer, and BFS finds it level by level, with the level number equal to the coin count. A visited array keeps it at O(amount * n) time and O(amount) space, the same as DP. DP is shorter to write, while BFS can exit early when it reaches the target.
How does the solution change if you must count the number of ways to make the amount?
That is Coin Change II. Replace min with a sum, so dp[i] += dp[i - coin]. Put the coin loop on the outside and the amount loop on the inside, so each combination is counted once. With the amount loop outside, you count ordered sequences, so 1+2 and 2+1 count separately.

Coin Change FAQ

What is the time complexity of Coin Change?

The memoized and bottom-up solutions run in O(amount * n), where n is the number of coin denominations. There are amount + 1 subproblems and each tries n coins. The plain recursion without a cache is exponential, bounded by n^amount.

Why use dynamic programming for Coin Change?

The best answer for an amount is 1 plus the best answer for some smaller amount, and the same smaller amounts appear in many branches. That is optimal substructure with overlapping subproblems. A table stores each amount's answer once, so the exponential tree becomes amount * n steps.

Why does the greedy approach fail for Coin Change?

Picking the biggest coin first only works for some coin systems. With coins [1, 3, 4] and amount 6, greedy takes 4 + 1 + 1 for three coins, while 3 + 3 uses two. Because coin values are arbitrary here, you have to compare all choices at every amount.

Can Coin Change be solved in O(1) extra space?

No, not in general. The recurrence for amount i needs the answers for i - coin for each coin, so you must remember past results. You can shrink the table to a rolling window as wide as the largest coin that is at most amount, but in the worst case that is still O(amount).

Why is the sentinel amount + 1 and not infinity?

The most coins any valid answer can use is amount, with all 1-coins, so amount + 1 can never be a real answer. It also fits in an int and adding 1 to it cannot overflow. In Python you can use float('inf'), but an integer sentinel keeps the types uniform.

What is the difference between Coin Change and Coin Change II?

Coin Change (LeetCode 322) asks for the fewest coins and uses min. Coin Change II asks for the number of combinations and uses addition with the coin loop outside the amount loop. Both fill a 1D array indexed by amount.

Asked at

See which companies ask this — Pro

Practise it