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 == 0 always has 1 valid combination (selecting zero coins), even when coins is empty.
  • When coins is empty and target > 0, no valid combination exists, so return 0.

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) <= 100
  • 1 <= coins[i] <= 10000
  • All values in coins are 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

  1. Restate the problem

    Given a list coins of distinct positive denominations (0 <= len(coins) <= 100, each in 1..10000) and a non-negative integer target (0 <= target <= 100), we want to count how many distinct multisets of coins sum to target when 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 = 0 always has 1 valid combination (selecting zero coins), even when coins is empty. - When coins is empty and target > 0, the answer is 0. - Return the exact integer with no modulo; the largest possible count under these bounds (coins = [1, 2, ..., 100], target = 100) is 190,569,292, well inside a signed 32-bit integer.

  2. Why a sum-first recurrence double-counts

    A tempting first formula is: "ways to reach amount = sum over every coin of ways to reach amount - coin." Try that on Example 1 (coins = [1, 2, 5], target = 6): for amount = 6, adding ways[5] (last coin 1) and ways[1] (last coin 5) counts both 5 + 1 and 1 + 5! Across 0..6, it computes 15 ordered sequences instead of 5 unordered 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 to coins[1] and never revisit coins[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 (2 copies of 1, 2 copies of 2, 0 copies of 5). However, it explores one leaf per valid combination — nearly 200 million leaves when coins = 1..100 and target = 100.

  3. 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 to amount using only the first i coins (coins[0 .. i - 1]). Consider the i-th coin coin = coins[i - 1]. Every combination summing to amount falls into one of two disjoint buckets:

    1. Uses 0 copies of coin: All coins come from the first i - 1 denominations. There are dp[i - 1][amount] such combinations.
    2. Uses 1 or more copies of coin (only possible when amount >= coin): Set aside one coin. What remains sums to amount - coin and may still include zero or more additional copies of coin, so there are dp[i][amount - coin] such combinations!

    Adding those two disjoint cases gives the recurrence with no loop over copies needed:

    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 0 coins (i = 0), dp[0][0] = 1 (the empty combination) and dp[0][amount] = 0 for amount > 0.

  4. 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 i only 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 list ways of length target + 1, updated in place from amount = coin upward to target: - Right before updating ways[amount], it still holds dp[i - 1][amount] (zero copies of coin). - Because amount - coin < amount and we sweep upward, ways[amount - coin] has already been updated in this coin's pass, so it holds dp[i][amount - coin] (one or more copies of coin). - If coin > target (say coin = 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]
    
  5. 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] reaches 4 during the coin = 2 pass: - 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 (reusing 2 up to three times automatically!). Finally, coin = 5 adds ways[1] = 1 ({1, 5}) to ways[6], yielding 5.

  6. 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 allocate ways in O(T) time and run one pass per coin over at most T amounts (amount from coin to T), doing a single O(1) addition at each step — at most 100 * 100 = 10,000 additions total.
  • Space: O(T). We store a single 1D list ways of length T + 1 (<= 101 integers), compressing what would otherwise be an O(n * T) 2D table down to one row.

Edge cases

  • Zero target (target = 0): Both coins = [] and non-empty coins return ways[0] = 1 (the single empty combination {}).
  • Empty coins with positive target (coins = [], target = 5): The outer loop runs zero times and returns ways[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, so ways[7] stays 0.
  • Unsorted coins ([6, 2, 3, 1]): Sorting coins is 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] with target = 100 counts the integer partitions of 100, equal to 190,569,292, which is well below 2^31 - 1 = 2,147,483,647.

Common mistakes

  • Putting amount in the outer loop and coin in the inner loop: Swapping the two loops counts ordered sequences (permutations) instead of unordered combinations, returning 15 instead of 5 on coins = [1, 2, 5], target = 6.
  • Sweeping amount downward (range(target, coin - 1, -1)): Reading ways[amount - coin] before updating it means each denomination can be used at most once (0/1 knapsack), returning 1 ({1, 5}) instead of 5 on Example 1.
  • Initializing ways[0] = 0: Every addition stays 0 + 0 = 0, breaking every positive target as well as target = 0.
  • Memoizing top-down recursion on remaining alone: Caching dfs(remaining) without coin_index in 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 row dp[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 of O(n * T) space instead of O(T).
  • Top-down recursion with memoization on (index, remaining): Caching dfs(i, rem) = dfs(i + 1, rem) + (dfs(i, rem - coins[i]) if rem >= coins[i] else 0) visits at most O(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 and for coin in coins: sits on the inside (if coin <= amount: ways[amount] += ways[amount - coin]). Now ways[amount] branches on which coin appears last in the sequence, counting [1, 5] (last coin 5) and [5, 1] (last coin 1) separately (15 sequences for Example 1). Because sequence counts grow exponentially (for coins = [1, 2], ways[T] follows the Fibonacci numbers and overflows 32-bit integers past T = 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 indices amount - coin have not yet been touched during the current coin's pass, ways[amount - coin] still holds the count excluding coin, 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 (using target + 1 as an unreachable sentinel, since even 1-unit coins require at most target coins), and relax min_coins[amount] = min(min_coins[amount], min_coins[amount - coin] + 1) as amount sweeps upward from coin to target. Return -1 if min_coins[target] > target else min_coins[target] in the same O(n * T) time and O(T) space.

Follow-up questions

Similar questions

More Worldquant interview questions

All 4 Worldquant questions →