Distinct Coin Combinations for a Target Sum
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
You are given an integer list coins of distinct positive coin values and a non-negative integer target. Assuming an unlimited supply of each coin value in coins, determine how many distinct unordered combinations of coins sum to target.
Order within a selection is irrelevant: two selections count as the same combination whenever they use the exact same number of copies of each denomination (for instance, [2, 1, 2] and [1, 2, 2] represent a single combination).
Implement count_coin_combinations(coins: List[int], target: int) -> int and return the exact integer count without applying any modulus:
- Reaching
target == 0always has1valid combination (selecting zero coins), even whencoinsis empty. - When
coinsis empty andtarget > 0, no valid combination exists, so return0.
Examples
Example 1
Input: coins = [1, 2, 5], target = 6
Output: 5
Five distinct multisets add up to 6: {5, 1}, {2, 2, 2}, {2, 2, 1, 1}, {2, 1, 1, 1, 1}, and {1, 1, 1, 1, 1, 1}.
Example 2
Input: coins = [4, 6], target = 7
Output: 0
Both available denominations are even, so any sum formed from them is even and cannot equal 7.
Example 3
Input: coins = [6, 2, 3, 1], target = 8
Output: 12
Denominations can appear in any order. Across {1, 2, 3, 6}, 12 distinct multisets sum to 8: 2 combinations containing a 6, 2 combinations containing two 3s, 3 combinations containing one 3 (and no 6), and 5 combinations using only 1s and 2s.
Constraints
0 <= len(coins) <= 1001 <= coins[i] <= 10000- All values in
coinsare pairwise distinct and may appear in arbitrary order. 0 <= target <= 100- Under these bounds, the exact answer always fits inside a signed 32-bit integer.
Step-by-step walkthrough
Restate the problem
Given a list
coinsof distinct positive denominations (0 <= len(coins) <= 100, each in1..10000) and a non-negative integertarget(0 <= target <= 100), we want to count how many distinct multisets of coins sum totargetwhen each denomination may be reused arbitrarily many times. A multiset is a collection where duplicate items are allowed (such as{2, 2, 1, 1}), and order is ignored ([2, 1, 2]and[1, 2, 2]are the exact same combination).Keep three boundary rules in mind: -
target = 0always has1valid combination (selecting zero coins), even whencoinsis empty. - Whencoinsis empty andtarget > 0, the answer is0. - Return the exact integer with no modulo; the largest possible count under these bounds (coins = [1, 2, ..., 100],target = 100) is190,569,292, well inside a signed 32-bit integer.Why a sum-first recurrence double-counts
A tempting first formula is: "ways to reach
amount= sum over everycoinof ways to reachamount - coin." Try that on Example 1 (coins = [1, 2, 5],target = 6): foramount = 6, addingways[5](last coin1) andways[1](last coin5) counts both5 + 1and1 + 5! Across0..6, it computes15ordered sequences instead of5unordered combinations.To count each combination only once, fix one canonical order across denominations: decide how many copies of
coins[0]to include (0, 1, 2, ...), then advance tocoins[1]and never revisitcoins[0]:def count_brute(coins: list, target: int) -> int: def helper(index: int, remaining: int) -> int: if index == len(coins): return 1 if remaining == 0 else 0 total = 0 copies = 0 while copies * coins[index] <= remaining: total += helper(index + 1, remaining - copies * coins[index]) copies += 1 return total return helper(0, target)This recursion is exact because
{2, 2, 1, 1}can only be formed along one branch (2copies of1,2copies of2,0copies of5). However, it explores one leaf per valid combination — nearly200 millionleaves whencoins = 1..100andtarget = 100.Key idea: count one denomination at a time in a table
Many recursive branches reach the exact same
(index, remaining)subproblem. Instead of recomputing them, we use dynamic programming — filling a table of answers to smaller subproblems from the ground up.Define
dp[i][amount]as the number of combinations summing toamountusing only the firsticoins (coins[0 .. i - 1]). Consider thei-th coincoin = coins[i - 1]. Every combination summing toamountfalls into one of two disjoint buckets:- Uses
0copies ofcoin: All coins come from the firsti - 1denominations. There aredp[i - 1][amount]such combinations. - Uses
1or more copies ofcoin(only possible whenamount >= coin): Set aside onecoin. What remains sums toamount - coinand may still include zero or more additional copies ofcoin, so there aredp[i][amount - coin]such combinations!
Adding those two disjoint cases gives the recurrence with no loop over
copiesneeded:dp[i][amount] = dp[i - 1][amount] + dp[i][amount - coin] (when amount >= coin) dp[i][amount] = dp[i - 1][amount] (when amount < coin)With
0coins (i = 0),dp[0][0] = 1(the empty combination) anddp[0][amount] = 0foramount > 0.- Uses
Compress the table to a single 1D row
Look at which two cells
dp[i][amount]reads:previous row (i - 1): ... [dp[i - 1][amount]] | v (+) current row (i): [dp[i][amount - coin]] ---> [dp[i][amount]]Row
ionly ever reads the cell directly above (dp[i - 1][amount]) and a cell earlier in the current row (dp[i][amount - coin]). That means we only need a single listwaysof lengthtarget + 1, updated in place fromamount = coinupward totarget: - Right before updatingways[amount], it still holdsdp[i - 1][amount](zero copies ofcoin). - Becauseamount - coin < amountand we sweep upward,ways[amount - coin]has already been updated in this coin's pass, so it holdsdp[i][amount - coin](one or more copies ofcoin). - Ifcoin > target(saycoin = 10000,target = 100),range(coin, target + 1)is empty and safely does nothing.def count_coin_combinations(coins: List[int], target: int) -> int: # ways[amount]: number of unordered coin combinations summing to 'amount' # using only the denominations processed so far (starts as [1, 0, 0, ...]). ways = [0] * (target + 1) # Base case: there is exactly 1 way to make amount 0 (choose zero coins). ways[0] = 1 # Outer loop over coins fixes one counting order across denominations so # [1, 2] and [2, 1] are counted once as a single combination, not twice. for coin in coins: # Sweep amount upward from 'coin' to 'target' so ways[amount - coin] # already reflects the current coin pass, allowing unlimited reuse of 'coin'. for amount in range(coin, target + 1): ways[amount] += ways[amount - coin] return ways[target]Trace through Example 1
Let's trace
coins = [1, 2, 5],target = 6:Stage ways[0..6] Combinations counted in ways[6] -------------- ----------------------- ------------------------------------------------ Start (0 coins) [1, 0, 0, 0, 0, 0, 0] (none yet; ways[0] = 1 is {}) After coin = 1 [1, 1, 1, 1, 1, 1, 1] {1,1,1,1,1,1} After coin = 2 [1, 1, 2, 2, 3, 3, 4] {1^6}, {1^4,2}, {1,1,2,2}, {2,2,2} After coin = 5 [1, 1, 2, 2, 3, 4, 5] {1^6}, {1^4,2}, {1,1,2,2}, {2,2,2}, {1,5}Notice how
ways[6]reaches4during thecoin = 2pass: -amount = 2:ways[2] += ways[0]->1 + 1 = 2. -amount = 4:ways[4] += ways[2]->1 + 2 = 3. -amount = 6:ways[6] += ways[4]->1 + 3 = 4(reusing2up to three times automatically!). Finally,coin = 5addsways[1] = 1({1, 5}) toways[6], yielding5.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def count_coin_combinations(coins: List[int], target: int) -> int: # ways[amount]: number of unordered coin combinations summing to 'amount' # using only the denominations processed so far (starts as [1, 0, 0, ...]). ways = [0] * (target + 1) # Base case: there is exactly 1 way to make amount 0 (choose zero coins). ways[0] = 1 # Outer loop over coins fixes one counting order across denominations so # [1, 2] and [2, 1] are counted once as a single combination, not twice. for coin in coins: # Sweep amount upward from 'coin' to 'target' so ways[amount - coin] # already reflects the current coin pass, allowing unlimited reuse of 'coin'. for amount in range(coin, target + 1): ways[amount] += ways[amount - coin] return ways[target]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine filling an envelope to reach 6 cents by walking past coin trays arranged in a strict one-way line — first the 1-cent tray, then the 2-cent tray, then the 5-cent tray — where you may scoop as many coins as you like from the tray in front of you, never stepping backward to an earlier tray. Because you must finish taking 1-cent coins before touching 2-cent coins, a multiset (a collection that allows duplicate items while ignoring order, like {1, 1, 2, 2}) can only ever be assembled in one fixed order (1, 1, 2, 2), never as 2, 1, 2, 1. We combine that one-way tray rule with dynamic programming — solving a counting problem by maintaining a compact array ways[0..target] of subproblem counts from 0 up to target instead of enumerating combinations individually.
The naive recurrence that loops over target amounts on the outside and tries every coin on the inside (ways[amount] += ways[amount - coin]) lets you add 1 then 5 and 5 then 1, overcounting ordered sequences (15 sequences instead of 5 combinations on Example 1). Meanwhile, recursively trying 0, 1, 2, ... copies of each denomination without a table visits one leaf per combination — nearly 200 million leaves when coins = 1..100 and target = 100.
Trace Example 1 (coins = [1, 2, 5], target = 6):
1. Start: ways = [1, 0, 0, 0, 0, 0, 0] (ways[0] = 1 represents choosing zero coins {}).
2. Pass coin 1 (amount = 1..6 upward): ways becomes [1, 1, 1, 1, 1, 1, 1] (all-1s combinations).
3. Pass coin 2 (amount = 2..6 upward): ways becomes [1, 1, 2, 2, 3, 3, 4]; then pass coin 5 (amount = 5, 6 upward) updates ways[5] += ways[0] (4) and ways[6] += ways[1] (5), returning 5.
Complexity
Let n = len(coins) (<= 100) and T = target (<= 100).
- Time:
O(n * T). We allocatewaysinO(T)time and run one pass per coin over at mostTamounts (amountfromcointoT), doing a singleO(1)addition at each step — at most100 * 100 = 10,000additions total. - Space:
O(T). We store a single 1D listwaysof lengthT + 1(<= 101integers), compressing what would otherwise be anO(n * T)2D table down to one row.
Edge cases
- Zero target (
target = 0): Bothcoins = []and non-emptycoinsreturnways[0] = 1(the single empty combination{}). - Empty
coinswith positive target (coins = [],target = 5): The outer loop runs zero times and returnsways[5] = 0. - Denominations larger than
target(coins = [10000],target = 100):range(10000, 101)is empty, so oversized coins are skipped cleanly without out-of-bounds indexing. - Unreachable target (
coins = [4, 6],target = 7): Even coins only ever add even indices to even indices and odd indices (0) to odd indices, soways[7]stays0. - Unsorted
coins([6, 2, 3, 1]): Sortingcoinsis unnecessary; any fixed order across distinct denominations defines a valid one-way tray order and yields the exact same count. - Maximum count without overflow:
coins = [1, 2, ..., 100]withtarget = 100counts the integer partitions of100, equal to190,569,292, which is well below2^31 - 1 = 2,147,483,647.
Common mistakes
- Putting
amountin the outer loop andcoinin the inner loop: Swapping the two loops counts ordered sequences (permutations) instead of unordered combinations, returning15instead of5oncoins = [1, 2, 5], target = 6. - Sweeping
amountdownward (range(target, coin - 1, -1)): Readingways[amount - coin]before updating it means each denomination can be used at most once (0/1 knapsack), returning1({1, 5}) instead of5on Example 1. - Initializing
ways[0] = 0: Every addition stays0 + 0 = 0, breaking every positive target as well astarget = 0. - Memoizing top-down recursion on
remainingalone: Cachingdfs(remaining)withoutcoin_indexin the cache key mixes choices from different stages and silently overcounts sequences. - Applying
% (10**9 + 7)out of habit: We must return the exact integer without modular reduction.
Alternative approaches
- Explicit 2D table
dp[n + 1][T + 1]: Storing every rowdp[i][amount] = dp[i - 1][amount] + (dp[i][amount - coin] if amount >= coin else 0)makes the transition explicit and helps reconstruct combinations, at the cost ofO(n * T)space instead ofO(T). - Top-down recursion with memoization on
(index, remaining): Cachingdfs(i, rem) = dfs(i + 1, rem) + (dfs(i, rem - coins[i]) if rem >= coins[i] else 0)visits at mostO(n * T)states, though recursion call overhead and dictionary lookups are slower than a flat 1D loop.
Follow-up questions
- How would the transition change if different orderings of the same coins counted as distinct sequences? Swap the two loops so
for amount in range(1, target + 1):sits on the outside andfor coin in coins:sits on the inside (if coin <= amount: ways[amount] += ways[amount - coin]). Nowways[amount]branches on which coin appears last in the sequence, counting[1, 5](last coin5) and[5, 1](last coin1) separately (15sequences for Example 1). Because sequence counts grow exponentially (forcoins = [1, 2],ways[T]follows the Fibonacci numbers and overflows 32-bit integers pastT = 45), sequence variants usually specify a prime modulus. - What adjustment is needed if each coin denomination in the input array may be used at most once? Keep
for coin in coins:as the outer loop, and reverse the inner loop to sweep downward:for amount in range(target, coin - 1, -1): ways[amount] += ways[amount - coin]. Because smaller indicesamount - coinhave not yet been touched during the current coin's pass,ways[amount - coin]still holds the count excludingcoin, ensuring each denomination contributes at most one copy (the classic 0/1 subset-sum counting pattern). - How would you modify the table if asked for the fewest coins needed to hit the target instead of the total number of combinations? Replace combination counts with minimum coin counts: initialize
min_coins = [0] + [target + 1] * target(usingtarget + 1as an unreachable sentinel, since even1-unit coins require at mosttargetcoins), and relaxmin_coins[amount] = min(min_coins[amount], min_coins[amount - coin] + 1)asamountsweeps upward fromcointotarget. Return-1ifmin_coins[target] > targetelsemin_coins[target]in the sameO(n * T)time andO(T)space.
Follow-up questions
- How would the transition change if different orderings of the same coins counted as distinct sequences?
- What adjustment is needed if each coin denomination in the input array may be used at most once?
- How would you modify the table if asked for the fewest coins needed to hit the target instead of the total number of combinations?
Similar questions
- OOP vs. Functional Python Enrichment Pipelines
- Expected Count of Strict Running Maxima
- Break-Even Fee for Four-Chest Prize Search
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses