Coin Change solution explained

Coin Change asks for the fewest coins that add up to a target amount when you may reuse each denomination as often as you like, or -1 if the amount cannot be made. Build a table where fewest[a] is the answer for amount a, and fill it from 1 upward with fewest[a] = 1 + the minimum of fewest[a - c] over every coin c that fits. That runs in O(amount × number of coins) time and O(amount) space, and it is correct where the greedy largest-coin-first rule is not.

By Published 8 min read

The task, restated

A ticket machine must hand back change using tokens of a few fixed values, and it has an endless supply of each. Customers hate pockets full of tokens, so the machine should pay each amount with as few tokens as possible. Write the function that, given the token values and the amount owed, returns that smallest count. If no combination reaches the amount exactly, return -1. An amount of 0 needs 0 tokens.

Examples made up for this page
CoinsAmountFewestOne best mix
[1, 4, 6]824 + 4 (greedy would use 6 + 1 + 1)
[1, 5, 6, 9]1125 + 6 (greedy would use 9 + 1 + 1)
[4, 9]1734 + 4 + 9
[2, 5, 10]1355 + 2 + 2 + 2 + 2
[3, 7]5-1No mix of 3s and 7s makes 5
[2, 5]00Nothing to pay
Examples made up for this page. Scroll sideways on a small screen.

Ask whether coin values are positive and distinct, how large the amount can get, and whether the interviewer wants the count only or also the coins used. The amount drives the cost of the table, so a huge amount with few coins may call for a different approach, which is worth saying even if you do not code it.

Why greedy is the trap

Many people first reach for the rule they use with cash: take the largest coin that fits, repeat. For many everyday currency systems that rule happens to be optimal, which is why it feels right. For an arbitrary set of coins it is not. The two greedy failures in the table above are the quickest way to show the interviewer you know this. Once greedy is ruled out, the question becomes how to consider every mix without trying them all one by one.

Brute force: try every first coin

The smallest count for an amount is one coin plus the smallest count for whatever is left after that coin. A recursion that tries each coin as the first one and keeps the best result is correct. Without a memo it revisits the same remaining amounts over and over, and the number of calls grows exponentially with the amount.

def fewest_tokens_slow(tokens, owed):
    if owed == 0:
        return 0
    best = -1
    for t in tokens:
        if t <= owed:
            sub = fewest_tokens_slow(tokens, owed - t)
            if sub != -1 and (best == -1 or sub + 1 < best):
                best = sub + 1
    return best
Plain recursion, exponential. A reference for small amounts only.

Optimal approach: fill a table from 0 up to the amount

Every call in the recursion asks the same kind of question about a smaller amount, and there are only amount + 1 different amounts. So compute each once, smallest first. Start with fewest[0] = 0 and mark every other amount as unreachable with a sentinel larger than any real answer, such as amount + 1. For each amount a from 1 up, look at each coin c that is no larger than a; if fewest[a - c] is reachable, fewest[a] may be fewest[a - c] + 1. Keep the smallest. At the end, the sentinel means -1.

Table for coins [1, 4, 6], amounts 0 to 8
AmountBest predecessorFewest
00
10 via coin 11
21 via coin 12
32 via coin 13
40 via coin 41
54 via coin 1 (or 1 via coin 4)2
60 via coin 61
76 via coin 12
84 via coin 42
Table for coins [1, 4, 6], amounts 0 to 8. Scroll sideways on a small screen.
def fewest_tokens(tokens, owed):
    unreachable = owed + 1
    fewest = [0] + [unreachable] * owed
    for a in range(1, owed + 1):
        for t in tokens:
            if t <= a and fewest[a - t] + 1 < fewest[a]:
                fewest[a] = fewest[a - t] + 1
    return -1 if fewest[owed] == unreachable else fewest[owed]
Python: bottom-up table, O(amount × coins) time, O(amount) space.
function fewestTokens(tokens, owed) {
  const unreachable = owed + 1;
  const fewest = new Int32Array(owed + 1).fill(unreachable);
  fewest[0] = 0;
  for (let a = 1; a <= owed; a++) {
    for (const t of tokens) {
      if (t <= a && fewest[a - t] + 1 < fewest[a]) {
        fewest[a] = fewest[a - t] + 1;
      }
    }
  }
  return fewest[owed] === unreachable ? -1 : fewest[owed];
}
JavaScript: the same table with a typed array.

Why amount + 1 works as the sentinel: the smallest coin is at least 1, so no real answer uses more than amount coins. Anything equal to amount + 1 must be the untouched starting value. Using infinity also works in Python, but a finite sentinel keeps the JavaScript typed array happy.

Another view: shortest path with BFS

Treat each amount from 0 to the target as a node and each coin as an edge from a to a + c. The fewest coins is the fewest edges from 0 to the target, and because every edge costs one coin, breadth-first search finds it. BFS can stop as soon as it reaches the target, which sometimes saves work, but its worst case matches the table. Mentioning it shows you can see the same problem as a graph, which interviewers like.

from collections import deque


def fewest_tokens_bfs(tokens, owed):
    if owed == 0:
        return 0
    seen = [False] * (owed + 1)
    seen[0] = True
    queue = deque([(0, 0)])  # (amount reached, tokens used)
    while queue:
        reached, used = queue.popleft()
        for t in tokens:
            nxt = reached + t
            if nxt == owed:
                return used + 1
            if nxt < owed and not seen[nxt]:
                seen[nxt] = True
                queue.append((nxt, used + 1))
    return -1
Python: BFS over amounts, same worst-case cost as the table.

Time and space

Cost for amount A and k coin values
VersionTimeExtra space
Plain recursionExponential in AO(A) stack
Recursion with a memoO(A · k)O(A) memo, O(A) stack
Bottom-up tableO(A · k)O(A)
BFS over amountsO(A · k) worst caseO(A)
Cost for amount A and k coin values. Scroll sideways on a small screen.

This is pseudo-polynomial: the cost grows with the numeric size of the amount, not with the number of digits in it. If the amount were in the billions, the table would be impractical, and you would say so.

Edge cases

  • Amount 0 returns 0, even with an empty coin list.
  • No coin list, positive amount: -1.
  • Amounts no coin mix can reach, such as odd amounts with only even coins: -1.
  • Coins larger than the amount are simply never used.
  • A coin of value 1 means every amount is reachable, so -1 cannot happen.
  • Duplicate coin values do no harm, only extra work.

Mistakes to avoid

  • Going greedy because it works on the first example.
  • Adding 1 to an unreachable entry and then treating the result as a real count. Check reachability first, or use a sentinel large enough that the comparison never wins.
  • Using float infinity in a language where integer arrays cannot hold it.
  • Mixing this problem up with counting the number of ways to make change. That version sums instead of minimizing, and the loop order changes whether different orders of the same coins count once or many times.
  • Recursion without a memo on large amounts, which times out and can also overflow the stack.

How to explain it out loud

Fictional example

From greedy to the table in three steps
Candidate
Largest coin first gives 6 plus 1 plus 1 for amount 8 with coins 1, 4 and 6, but 4 plus 4 is two coins, so greedy is out.
Candidate
The best way to pay any amount is one coin plus the best way to pay what remains. There are only amount plus one different remainders, so I fill a table from zero upward.
Candidate
That is amount times number-of-coins time and linear space in the amount. I will use amount plus one as my unreachable marker and turn it into minus one at the end.

Maximum Product Subarray is a different kind of DP, where you carry two values forward because a negative can flip the best into the worst. Decode Ways looks back a fixed one or two steps and counts instead of minimizing. House Robber is the simplest look-back table in this set and a good warm-up before this one.

Where Natively fits

Coin Change rewards saying the greedy counterexample out loud before you code. During practice on Mac or Windows, Natively can read the problem from a screenshot, suggest the table approach with code to compare, and record a transcript of how you talked through it. Reading that transcript later tells you whether you ruled out greedy with an example or only claimed it. More on the AI interview assistant page.

Questions people ask

How do you solve Coin Change with dynamic programming?

Make a table fewest[0..amount] with fewest[0] = 0 and every other entry unreachable. For each amount a from 1 up, try every coin c no larger than a and keep the smallest fewest[a - c] + 1. Return -1 if the target stays unreachable.

Why does a greedy algorithm fail for Coin Change?

Taking the largest coin first is only optimal for some coin systems. With coins 1, 4 and 6 and an amount of 8, greedy uses 6 + 1 + 1, three coins, while 4 + 4 uses two.

What is the time complexity of Coin Change?

O(amount × number of coins) time and O(amount) space for the bottom-up table. It is pseudo-polynomial because it grows with the size of the amount itself.

Can Coin Change be solved with BFS?

Yes. Treat each amount as a node and each coin as an edge that adds its value. Breadth-first search from 0 reaches the target in the fewest edges, which is the fewest coins.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP