Forward Deployed EngineeringCoding and AlgorithmsDynamic Programming
Coin change: fewest coins to make an amount.
Question 7 of 9 · Updated
On this page
Interview-ready answer#
I would first clarify that the denominations are positive integers, the target is a nonnegative integer, and each coin can be used an unlimited number of times. We must make the exact amount using the fewest coins, returning -1 if it is impossible.
I would use bottom-up dynamic programming rather than greedy selection, because taking the largest coin first is not always optimal. Define dp[x] as the minimum coins needed to make amount x. Initialize dp[0] = 0 and all other states as unreachable. For each amount, try every coin that fits, and choose the minimum of dp[x - coin] + 1. Since each coin is positive, the transition always refers to a smaller amount whose optimal solution has already been computed. This gives O(nA) time and O(A) auxiliary space, where n is the number of denominations and A is the target amount.
Why greedy fails#
With denominations [1, 3, 4] and target 6, greedy takes 4 + 1 + 1, requiring three coins. The optimal solution is 3 + 3, requiring two. Greedy is valid for some denomination systems, but not arbitrary ones.
Dynamic programming recurrence and correctness#
dp[0] = 0
dp[x] = min(dp[x - c] + 1 for each coin c <= x)If no reachable predecessor exists, the state remains unreachable. Any optimal solution for x contains a final coin c; removing it leaves a solution for x-c. That remainder must itself be optimal, otherwise replacing it with a better solution would improve the original solution. Conversely, adding c to an optimal reachable predecessor produces a valid solution for x. Taking the minimum over all choices therefore yields the optimum.
For [1, 3, 4], the states for amounts 0 through 6 are:
| Amount | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Minimum coins | 0 | 1 | 2 | 1 | 1 | 2 | 2 |
Python implementation#
PYTHONdef coin_change(coins: list[int], amount: int) -> int: if amount < 0 or any(c <= 0 for c in coins): raise ValueError('Expected a nonnegative amount and positive denominations') dp = [0] + [amount + 1] * amount for value in range(1, amount + 1): for coin in coins: if coin <= value: dp[value] = min(dp[value], dp[value - coin] + 1) return dp[amount] if dp[amount] <= amount else -1 print(coin_change([1, 2, 5], 11)) # 3: 5 + 5 + 1 print(coin_change([1, 3, 4], 6)) # 2: 3 + 3 print(coin_change([2], 3)) # -1 print(coin_change([], 0)) # 0
The sentinel amount + 1 is safe because a reachable positive integer amount A requires at most A coins of positive integer value. Unreachable states cannot improve any finite optimum. Ascending iteration allows a denomination to be reused. The function assumes integer inputs as specified in the problem; its explicit validation rejects negative amounts and nonpositive denominations.
Local verification: 7,946 checks passed: all 256 subsets of denominations 1 through 8 for amounts 0 through 30 (7,936 comparisons against an independently implemented BFS), seven explicit examples and edge cases, and three invalid-input checks. This establishes correctness on the tested cases, not every possible input.
Complexity and alternatives#
- Bottom-up DP: O(nA) time and O(A) auxiliary space (plus constant overhead for zero amount; validation takes O(n)).
- Memoized recursion: the same worst-case DP bounds, with additional recursion stack usage; it can avoid visiting irrelevant states but may hit recursion limits.
- BFS: treat each amount as a vertex and adding a denomination as a unit-cost edge. The first arrival at A is a shortest path; worst-case O(nA) time and O(A) space.
- The DP is pseudo-polynomial: A is the numeric target, not its bit length. Very large targets may make it impractical.
Production considerations for an FDE#
Suppose a customer needs to fulfill an exact order quantity using standardized package sizes while minimizing handling operations. Coin change is a useful model only if package sizes are positive integers, supply is unlimited, exact fulfillment is required, and every package has the same handling cost. For real deployment, confirm these assumptions first. Inventory limits require bounded optimization; different package costs require a cost-weighted objective, and permitting overfill changes the feasible set. Avoid floating-point currency arithmetic by using integer minor units where appropriate.
Before allocating a large DP array, deduplicate denominations, remove those above the target, and check the greatest common divisor (GCD) of the remaining positive denominations. For a positive target, an empty remaining set is impossible; if the GCD does not divide the target, no solution exists. If it divides, scale the denominations and target by the GCD to reduce states; divisibility alone does not guarantee feasibility. Set resource limits and choose a specialized optimization approach for very large targets. Validate against representative customer orders and track exact-fill feasibility, runtime, and the actual business cost rather than assuming fewer packages always means lower cost.
Likely interviewer follow-ups#
- Return the selected coins: store the denomination chosen for each improved state, then follow predecessors from A to 0. If unreachable, return no combination.
- Limited coin supply: use a bounded-knapsack approach, with each denomination's available quantity explicitly represented.
- Count combinations instead of minimizing: initialize
ways[0] = 1, then iterate denominations in the outer loop and amounts in ascending order, accumulating counts. Deduplicate equal denominations to avoid overcounting indistinguishable coin types. - Can you use greedy? Only with a denomination system for which the greedy-choice property is established; the counterexample above disproves general correctness.
References
- 1.LeetCode 322 — Coin Change (not live-verified)leetcode.com
- 2.CP-Algorithms — Knapsack Problem (not live-verified)cp-algorithms.com
- 3.FDE Interviews — source questionfdeinterviews.com
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models