← Back to Algorithms, page 4

algorithms-0080 · Medium mid

Coin change: find the fewest coins that make a target amount with unlimited coins of each denomination, explain why greedy fails, and count the number of combinations.

Let dp[a] be the fewest coins for amount a: dp[0] = 0 and dp[a] = 1 + min(dp[a - c]) over coins c <= a. Filling a from 1 to the target takes O(amount * coins) time and O(amount) space; an unreachable amount stays at the sentinel and returns -1. Greedy (largest coin first) fails for coins like [1, 3, 4] and amount 6. Counting combinations puts coins in the outer loop so each combination is counted once.

Full answer

Problem

Given coin values and an amount, return the fewest coins that sum to the amount (each coin may be used any number of times), or -1 if impossible. Follow-up: return the number of combinations that make the amount.

Example: coins [1, 2, 5], amount 11 returns 3 (5 + 5 + 1). Coins [2], amount 3 returns -1. Coins [1, 3, 4], amount 6 returns 2 (3 + 3), while greedy picks 4 + 1 + 1. Coins [1, 2, 5] have 4 combinations for amount 5.

Constraints: 1 <= len(coins) <= 12, coin values up to 2^31 - 1, 0 <= amount <= 10^4.

Brute force

Recursively try every coin at every step: f(a) = 1 + min(f(a - c)). Without memoization the branching factor is the number of coins and the depth is up to the amount, which is exponential.

BFS over remaining amounts is a valid alternative: each level adds one coin, so the first time 0 is reached gives the answer; it is used as the reference in the tests.

Optimal approach

Bottom-up table:

  1. dp = [0] + [INF] * amount with INF = amount + 1 (more coins than could ever be needed).
  2. For a in 1..amount, for each coin c <= a: dp[a] = min(dp[a], dp[a - c] + 1).
  3. Return dp[amount] if it is below INF, else -1.

Counting combinations: ways = [1] + [0] * amount; for each coin c (outer loop), for a in c..amount: ways[a] += ways[a - c].

Why it works

Any optimal way to make a ends with some last coin c, and the rest is an optimal way to make a - c (otherwise swapping in a better one would improve the total). So taking the minimum over all possible last coins gives the answer, and amounts are filled in increasing order so every dp[a - c] is ready. For counting, processing coin by coin means each combination is built in a fixed coin order, so 1 + 2 and 2 + 1 are the same entry.

Complexity

O(amount * len(coins)) time and O(amount) space for both versions. This is pseudo-polynomial: it depends on the numeric value of the amount, not the input length.

Code

python
import random
from collections import deque


def coin_change(coins, amount):
    """Fewest coins to make amount, or -1. Unbounded supply. O(amount * len(coins)) time, O(amount) space."""
    INF = amount + 1
    dp = [0] + [INF] * amount            # dp[a] = fewest coins for a
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and dp[a - c] + 1 < dp[a]:
                dp[a] = dp[a - c] + 1
    return dp[amount] if dp[amount] < INF else -1


def count_ways(coins, amount):
    """Number of combinations (order ignored). Coins in the outer loop avoids counting 1+2 and 2+1 twice."""
    ways = [1] + [0] * amount
    for c in coins:
        for a in range(c, amount + 1):
            ways[a] += ways[a - c]
    return ways[amount]


def greedy(coins, amount):
    """Largest coin first. Correct for some coin systems only."""
    n = 0
    for c in sorted(coins, reverse=True):
        n += amount // c
        amount %= c
    return n if amount == 0 else -1


def brute_bfs(coins, amount):
    """BFS over remaining amounts: the first time 0 is reached uses the fewest coins."""
    seen, q = {amount}, deque([(amount, 0)])
    while q:
        a, k = q.popleft()
        if a == 0:
            return k
        for c in coins:
            if a - c >= 0 and a - c not in seen:
                seen.add(a - c)
                q.append((a - c, k + 1))
    return -1


if __name__ == "__main__":
    assert coin_change([1, 2, 5], 11) == 3
    assert coin_change([2], 3) == -1
    assert coin_change([1], 0) == 0
    assert coin_change([1, 3, 4], 6) == 2 and greedy([1, 3, 4], 6) == 3   # greedy gives 4+1+1
    assert count_ways([1, 2, 5], 5) == 4
    rng = random.Random(80)
    for _ in range(500):
        coins = rng.sample(range(1, 15), rng.randint(1, 4))
        amt = rng.randint(0, 60)
        assert coin_change(coins, amt) == brute_bfs(coins, amt)
    print("all tests passed")

Save as b80_coin_change.py and run python3 b80_coin_change.py. It prints all tests passed (Python 3.13.5).

Edge cases

Amount 0 (0 coins, 1 combination). No combination possible (-1). Coins larger than the amount (skipped). Duplicate coin values. Greedy works for canonical systems such as [1, 5, 10, 25] but not in general.

Pattern

Unbounded knapsack: each item can be used repeatedly, so the inner loop over amounts runs upward. Swapping the loop order changes what is counted (permutations versus combinations). Related problems: perfect squares, minimum cost tickets, and integer break.

python
import random
from collections import deque


def coin_change(coins, amount):
    """Fewest coins to make amount, or -1. Unbounded supply. O(amount * len(coins)) time, O(amount) space."""
    INF = amount + 1
    dp = [0] + [INF] * amount            # dp[a] = fewest coins for a
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and dp[a - c] + 1 < dp[a]:
                dp[a] = dp[a - c] + 1
    return dp[amount] if dp[amount] < INF else -1


def count_ways(coins, amount):
    """Number of combinations (order ignored). Coins in the outer loop avoids counting 1+2 and 2+1 twice."""
    ways = [1] + [0] * amount
    for c in coins:
        for a in range(c, amount + 1):
            ways[a] += ways[a - c]
    return ways[amount]


def greedy(coins, amount):
    """Largest coin first. Correct for some coin systems only."""
    n = 0
    for c in sorted(coins, reverse=True):
        n += amount // c
        amount %= c
    return n if amount == 0 else -1


def brute_bfs(coins, amount):
    """BFS over remaining amounts: the first time 0 is reached uses the fewest coins."""
    seen, q = {amount}, deque([(amount, 0)])
    while q:
        a, k = q.popleft()
        if a == 0:
            return k
        for c in coins:
            if a - c >= 0 and a - c not in seen:
                seen.add(a - c)
                q.append((a - c, k + 1))
    return -1


if __name__ == "__main__":
    assert coin_change([1, 2, 5], 11) == 3
    assert coin_change([2], 3) == -1
    assert coin_change([1], 0) == 0
    assert coin_change([1, 3, 4], 6) == 2 and greedy([1, 3, 4], 6) == 3   # greedy gives 4+1+1
    assert count_ways([1, 2, 5], 5) == 4
    rng = random.Random(80)
    for _ in range(500):
        coins = rng.sample(range(1, 15), rng.randint(1, 4))
        amt = rng.randint(0, 60)
        assert coin_change(coins, amt) == brute_bfs(coins, amt)
    print("all tests passed")

Minimum-coins table, combination count, the greedy counterexample, and a BFS reference on random coin sets.

Complexity

Time: O(amount * len(coins)). Space: O(amount). Pseudo-polynomial in the amount; BFS has the same bound but often stops early.

By level

Fresher: Writes the bottom-up table and shows with a counterexample why greedy is wrong. Handles the -1 case.

Mid: Adds the combinations count with the correct loop order and reconstructs the coins used. Explains the pseudo-polynomial bound.

Senior: Discusses when canonical coin systems allow greedy, memory for very large amounts, and BFS as an early-exit alternative. Relates the problem to unbounded knapsack and change-making in payment systems.

Key points

  • dp[a] = 1 + min over coins of dp[a - c]
  • Sentinel amount + 1 marks unreachable
  • Greedy fails for non-canonical coins
  • Coins in the outer loop count combinations
  • Pseudo-polynomial time

Common mistakes

  • Trusting greedy
  • Using float('inf') and then returning it
  • Swapping loops and counting permutations instead of combinations
  • Forgetting amount 0

Follow-ups

  • How would you return the actual coins used?
  • How do you count ordered sequences instead of combinations?
  • What if each coin can be used at most once?

Tips

  • Show the [1, 3, 4] counterexample
  • Explain the loop order for counting
  • Mention pseudo-polynomial time

Evaluation rubric

  • Correct DP
  • Handles impossible amounts
  • Explains greedy failure
  • Correct counting variant