ToolMight Logo
MediumDynamic ProgrammingBottom-Up TabulationUnbounded Knapsack

Coin Change

Find the minimum number of coins required to form a target amount. Compare top-down memoized search against bottom-up unbounded knapsack tabulation.

Optimal Time
O(S * n)
Optimal Space
O(S)
Primary Pattern
Bottom-Up Tabulation
Visualizer
Open Interactive View →

Problem Statement

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Examples & Constraints

Example 1
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1. Total 3 coins.
Example 2
Input: coins = [2], amount = 3
Output: -1
Explanation: Amount 3 cannot be formed using only coins of denomination 2.
Constraints
  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4

Pattern Recognition & Core Invariant

How to Spot This Pattern

Minimizing or counting choices from unlimited denominations to reach a scalar target matches Unbounded Knapsack DP whenever greedy selection fails.

Core Invariant

dp[a] represents the fewest coins needed to make amount a; testing every coin c <= a gives dp[a] = min(dp[a], 1 + dp[a - c]) from dp[0] = 0.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Top-Down DFS with Memoization
O(S * n)O(S)Recursively evaluate solve(rem) = 1 + min(solve(rem - coin)) across all denominations while caching previously solved remainders.
2. Bottom-Up Dynamic Programming (Tabulation)Optimal
O(S * n)O(S)Build an array dp where dp[i] represents the minimum coins needed for amount i. For each amount, test all coins and pick the minimum of 1 + dp[i - coin] in O(amount * len(coins)) time.

1. Top-Down DFS with Memoization

TimeO(S * n)
SpaceO(S)

Recursively evaluate solve(rem) = 1 + min(solve(rem - coin)) across all denominations while caching previously solved remainders.

Time ComplexityO(S * n)

At most S distinct remainder states (1..amount) are evaluated, each branching over n coins.

Space ComplexityO(S)

Memo cache holds up to S entries plus up to S recursion depth.

How It Works

Caching Optimal Substructure Top-Down

For any remaining amount rem:

  • If rem == 0, 0 additional coins are needed.
  • If rem < 0, that branch is invalid (return sentinel INT_MAX / infinity).
  • Otherwise try every coin <= rem and cache the minimum 1 + solve(rem - coin) inside memo[rem].

This solves only reachable remainders cleanly via recursion.

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Start at solve(11)

Try coins 1, 2, 5 -> branches down solve(10), solve(9), solve(6).

State:solve(11) -> branching
Strengths
  • +Skips unreachable remainder states if denominations are large
  • +Reads directly like the recursive math formula
Trade-offs
  • -Recursion stack overhead up to O(amount) calls (~10^4 depth)

Reference Implementation

Complete implementation for Top-Down DFS with Memoization in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def coin_change_memo(coins: list[int], amount: int) -> int:
INF = amount + 1
memo = {}
def dfs(rem: int) -> int:
if rem == 0:
return 0
if rem < 0:
return INF
if rem in memo:
return memo[rem]
best = INF
for c in coins:
best = min(best, 1 + dfs(rem - c))
memo[rem] = best
return best
ans = dfs(amount)
return ans if ans <= amount else -1

2. Bottom-Up Dynamic Programming (Tabulation)

Optimal
TimeO(S * n)
SpaceO(S)

Build an array dp where dp[i] represents the minimum coins needed for amount i. For each amount, test all coins and pick the minimum of 1 + dp[i - coin] in O(amount * len(coins)) time.

Time ComplexityO(S * n)

Where S is the target amount and N is the number of coin denominations. The outer loop runs S times, and the inner loop checks N coins.

Space ComplexityO(S)

Consumes an array dp of size amount + 1 to store subproblem solutions.

How It Works

Why Greedy Fails for Arbitrary Coins

Humans naturally try to pick the largest coin first (Greedy approach).
For example, with coins [1, 3, 4] and amount 6:

  • Greedy picks 4 then 1 then 1 = 3 coins (4 + 1 + 1).
  • But the optimal combination is 3 + 3 = 2 coins!

Because greedy choices do not guarantee the global optimum for arbitrary denominations, we must evaluate overlapping subproblems using Dynamic Programming.


The Recurrence Relation:

Let dp[a] be the minimum coins needed to make amount a.

  1. Base Case: dp[0] = 0 (zero coins needed to form amount 0).
  2. Initialize all other entries dp[1..amount] with an infinity sentinel (amount + 1).
  3. For each amount a from 1 to amount:
  • For each coin c in coins:
  • If a - c >= 0: dp[a] = min(dp[a], 1 + dp[a - c])
  1. If dp[amount] > amount, the target cannot be formed; return -1. Otherwise, return dp[amount].

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1dp Array Init (amount = 11, coins = [1, 2, 5])

dp of size 12 initialized. dp[0] = 0, all others initialized to infinity (12).

State:dp[0] = 0dp[1..11] = 12
Strengths
  • +Optimal O(S * n) runtime
  • +Clean bottom-up array iteration avoiding recursion overhead
Trade-offs
  • -Consumes O(S) auxiliary memory proportional to the target amount

Reference Implementation

Complete implementation for Bottom-Up Dynamic Programming (Tabulation) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def coin_change(coins: list[int], amount: int) -> int:
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for a in range(1, amount + 1):
for c in coins:
if a - c >= 0:
dp[a] = min(dp[a], 1 + dp[a - c])
return dp[amount] if dp[amount] <= amount else -1
if __name__ == "__main__":
print("test1 (11):", coin_change([1, 2, 5], 11))
print("test2 (3):", coin_change([2], 3))
print("test3 (0):", coin_change([1], 0))
Interactive Visualizer

Trace Complexity Analysis mechanics in memory

Step through custom inputs in the Complexity Analysis visualizer to inspect pointer updates, array shifts, and call-stack state alongside Coin Change.

Open Complexity Analysis visualizer

Frequently Asked Questions

Why does the Greedy coin approach fail for general denominations?

Greedy picks the largest denomination first. With coins = [1, 3, 4] and amount = 6, greedy yields 4 + 1 + 1 (3 coins), whereas 3 + 3 uses only 2 coins. DP explores overlapping remainders to find the true minimum.

Why initialize the dp array with amount + 1 instead of Integer.MAX_VALUE?

Because the smallest valid coin is >= 1, no valid combination needs more than amount coins. Using amount + 1 represents infinity without integer overflow when computing 1 + dp[a - c].

Does loop order (outer amount vs outer coin) matter here?

For minimum coin count (min), both outer-amount and outer-coin loops produce the same answer. In Coin Change II (counting distinct combinations), outer-coin is mandatory so permutations aren't double-counted.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • amount = 0 always returns 0 coins immediately without entering loops.
  • Greedy trap: coins = [1, 3, 4], amount = 6 gives 2 (3 + 3), whereas greedy (4 + 1 + 1) yields 3.
  • Impossible target (coins = [2], amount = 3) leaves dp[amount] > amount and returns -1.
  • Coin denomination larger than amount (e.g. coin = 2^31 - 1, amount = 5) is skipped by `c <= a` without overflow.

Common Bugs to Avoid

  • Using greedy largest-coin selection instead of exploring all denominations with DP.
  • Initializing dp entries with INT_MAX and computing `1 + dp[a - c]` directly, triggering signed integer overflow.
  • Returning -1 instead of 0 when target amount is 0.

Interview Follow-Up Variations

  • Coin Change II: count distinct combinations (put `for coin in coins` OUTSIDE `for a in range(coin, amount+1)` so order doesn't create permutations).
  • Reconstruct which coins formed the minimum count by saving `parentCoin[a] = c` whenever `dp[a]` improves.

Related Problems

All problems
EasyDynamic Programming

Climbing Stairs

Count distinct ways to climb n stairs taking 1 or 2 steps at a time. Progress from top-down memoization to O(1)-space Fibonacci dynamic programming.

Pattern: Fibonacci Sequence
O(n) · O(1)
Solve
MediumDynamic Programming

Maximum Subarray (Kadane's Algorithm)

Find the contiguous subarray with the largest integer sum. Compare quadratic prefix enumeration against Kadane's linear-time reset invariant.

Pattern: Kadane's Algorithm
O(n) · O(1)
Solve