Coin Change II solution explained

Coin Change II counts how many different combinations of coins add up to a target amount, when every coin value can be used as often as you like and the order of coins does not matter. Keep an array where ways[t] is the number of combinations that make t, start with ways[0] = 1, and for each coin value add ways[t - coin] into ways[t] for t from the coin upward. Putting the coin loop outside the amount loop is what counts each combination once; swapping the loops counts orderings instead.

By Published 7 min read

The problem, restated

A vending machine has to give back a certain amount in change. It holds unlimited coins of a few distinct values. How many different collections of coins add up to exactly that amount? A collection is what ends up in your hand, so 1 + 3 and 3 + 1 are the same collection. You are counting combinations, not the fewest coins and not sequences.

Examples written for this page (coin values are plain numbers)
AmountCoin valuesCombinationsThe combinations
71, 3, 451 x 7; 3 + 1 x 4; 3 + 3 + 1; 4 + 1 x 3; 4 + 3
123, 5, 723 x 4; 5 + 7
82, 432 x 4; 4 + 2 + 2; 4 + 4
320No mix of 2s makes an odd amount
051The empty collection
Examples written for this page (coin values are plain numbers). Scroll sideways on a small screen.

Why it gets asked

Its sibling, the minimum-coins version, is more famous, so this one tests whether you notice the question changed. Counting combinations instead of minimizing changes the operation from min to plus and the base case from zero coins to one way. More importantly, it has a trap that separates people who memorized a loop from people who understand it: the order of the two loops decides whether you count combinations or orderings.

Follow-ups

  • Count orderings instead. Swap the loops: amounts outside, coins inside. Climbing-stairs style problems want this version.
  • Each coin may be used at most once. Run the inner loop downward, the same trick as the 0/1 knapsack.
  • Fewest coins instead of number of ways. Replace plus with min, start every entry at infinity except ways[0] = 0, and add one per coin used.
  • The count gets very large. Many versions promise the answer fits in a 32-bit integer or ask for it modulo a large prime; Python integers grow, and JavaScript numbers stay exact up to 2^53.
  • The coin list contains a duplicate value. Ask or remove duplicates first, since a repeated value would count the same collections twice.

Brute force

Decide coin by coin how many copies to use. For the first value, try zero copies, one copy, two, and so on while the total stays within the amount, then recurse on the remaining values with what is left. Because each value is handled once, in a fixed order, every collection is produced exactly once. The work grows quickly with the amount and the number of values, and the same (remaining values, remaining amount) pairs are solved many times.

def count_combinations_slow(amount, coins, i=0):
    if amount == 0:
        return 1
    if i == len(coins):
        return 0
    total, copies = 0, 0
    while copies * coins[i] <= amount:
        total += count_combinations_slow(amount - copies * coins[i], coins, i + 1)
        copies += 1
    return total
Python: choose a count for each coin value in turn. Correct, slow.

The optimal approach: one array, coins on the outside

Think of a two-dimensional table first: cell (k, t) counts the collections that make t using only the first k coin values. Either the k-th value is not used at all, which is cell (k - 1, t), or it is used at least once, which leaves t - coin to make with the same first k values, cell (k, t - coin). Add the two. This is the unbounded knapsack pattern in its counting form. Each row only reads the row above and earlier cells in its own row, so one array updated in place, left to right, holds exactly that table.

def count_combinations(amount, coins):
    ways = [0] * (amount + 1)
    ways[0] = 1  # one way to make 0: take no coins
    for coin in coins:  # coins outside: each collection counted once
        for total in range(coin, amount + 1):  # upward: a coin may repeat
            ways[total] += ways[total - coin]
    return ways[amount]
Python: combinations. O(amount · number of coins) time, O(amount) memory.
function change(amount, coins) {
  const ways = new Array(amount + 1).fill(0);
  ways[0] = 1;
  for (const coin of coins) {
    for (let total = coin; total <= amount; total++) {
      ways[total] += ways[total - coin];
    }
  }
  return ways[amount];
}
JavaScript: the same loops.
The ways array for amount 7 after each coin value is added
After01234567
Start10000000
Coin 111111111
Coin 311122233
Coin 411123345
The ways array for amount 7 after each coin value is added. Scroll sideways on a small screen.

Read the last column. With only the value 1 there is one way to make 7. Adding 3 brings in the collections with at least one 3, which brings the count to 3. Adding 4 brings in the two collections with a 4, for a final 5.

The loop-order trap

Swap the loops so the amount is outside and the coins inside, and the code still looks reasonable. But now, for each total, it asks which coin came last, and a different last coin counts as a different answer. That counts sequences. For amount 4 with values 1 and 2 the correct answer is 3 (1 + 1 + 1 + 1, 1 + 1 + 2, 2 + 2), while the swapped version returns 5, because it counts 1 + 1 + 2, 1 + 2 + 1 and 2 + 1 + 1 separately.

def count_orderings(amount, coins):
    ways = [0] * (amount + 1)
    ways[0] = 1
    for total in range(1, amount + 1):  # amounts outside: order matters
        for coin in coins:
            if coin <= total:
                ways[total] += ways[total - coin]
    return ways[amount]
Python: the swapped loops, which count orderings, not combinations.

A one-line way to remember it: with coins on the outside, by the time a coin is processed, the array only knows about earlier coins and copies of this one, so every collection is built in one fixed order. With amounts outside, every coin is available at every step, so every arrangement is built.

Complexity

A is the amount and k the number of coin values
ApproachTimeExtra memory
Choose a count per value, plain recursionExponential in k, grows with AO(k) stack
Memoized recursion on (index, remaining)O(k · A) states, each looping over copiesO(k · A)
Two-dimensional tableO(k · A)O(k · A)
One array, coins outsideO(k · A)O(A)
A is the amount and k the number of coin values. Scroll sideways on a small screen.

Edge cases

  • Amount 0 returns 1, even with an empty coin list.
  • A positive amount with no coins returns 0.
  • Coin values larger than the amount, which the inner loop simply skips.
  • No value divides the amount and no mix reaches it, which returns 0.

Common mistakes

  • Putting the amount loop outside, which counts orderings.
  • Starting ways[0] at 0, which makes every count 0.
  • Running the inner loop downward, which forbids reusing a coin.
  • Reusing the minimum-coins code and changing only the min to a plus, keeping its infinity initial values.

How to explain it out loud

Fictional example

Saying why the loops are in this order
Candidate
We want collections, so order should not matter. I will keep ways of t for every total up to the amount, with ways of zero equal to one for the empty collection.
Candidate
I process one coin value at a time and, for each total from that value upward, add the ways to make total minus the coin. Going upward lets the same coin be used again.
Candidate
The coin loop has to be on the outside. If I put the totals outside, I would count 1 plus 2 and 2 plus 1 as different. It is amount times the number of coin values in time and amount in memory.

Partition Equal Subset Sum is the 0/1 cousin: each number used once, so its inner loop runs downward. Target Sum counts subsets that hit a value, the counting version of that 0/1 table. Word Break also builds a total from reusable pieces, but asks only whether one way exists.

Practicing with Natively

The loop order is easy to get right by luck and hard to defend under questioning, so rehearse the explanation. In practice sessions, Natively on Mac or Windows can read the prompt from a screenshot and suggest an approach to check against your own, and the transcript of a mock lets you hear whether you explained the order before the interviewer had to ask. See the AI interview assistant.

Questions people ask

How do you solve Coin Change II?

Keep ways[t], the number of combinations that make t, with ways[0] = 1. For each coin value in an outer loop, go through totals from the coin value up to the amount and add ways[t - coin] into ways[t]. The answer is ways[amount].

Why does the coin loop have to be the outer loop?

With coins outside, each combination is built in one fixed coin order, so it is counted once. With amounts outside, the same coins in a different order count as different answers, which gives the number of orderings instead.

What is the time complexity of Coin Change II?

O(A · k) time and O(A) memory, where A is the amount and k is the number of coin values.

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

The first asks for the fewest coins that make the amount, using min over choices. The second asks how many different combinations make it, using a sum, with ways[0] = 1 as the base case.

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