Dynamic programming
coin change problem
algorithm
programming tutorial
computational solutions

Coin change DP solution to keep track of coins

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The coin change dynamic programming problem is often solved for minimum coin count, but many implementations stop there and do not return which coins were used. In practical applications, you usually need both: optimal count and exact composition. The standard fix is to keep a "parent" or "choice" array while computing DP so you can reconstruct the selected coins at the end. This keeps time complexity manageable and makes the solution useful for real outputs rather than just numeric scores.

Core Sections

DP for minimum number of coins

For amount A, let dp[x] be minimum coins to make value x.

python
1def min_coin_count(coins, amount):
2    INF = amount + 1
3    dp = [INF] * (amount + 1)
4    dp[0] = 0
5
6    for x in range(1, amount + 1):
7        for c in coins:
8            if c <= x:
9                dp[x] = min(dp[x], dp[x - c] + 1)
10
11    return -1 if dp[amount] == INF else dp[amount]

This gives count, not the actual set of coins.

Track coin choices for reconstruction

Store which coin produced the best state at each amount.

python
1def min_coin_with_path(coins, amount):
2    INF = amount + 1
3    dp = [INF] * (amount + 1)
4    choice = [-1] * (amount + 1)
5    dp[0] = 0
6
7    for x in range(1, amount + 1):
8        for c in coins:
9            if c <= x and dp[x - c] + 1 < dp[x]:
10                dp[x] = dp[x - c] + 1
11                choice[x] = c
12
13    if dp[amount] == INF:
14        return -1, []
15
16    used = []
17    cur = amount
18    while cur > 0:
19        c = choice[cur]
20        used.append(c)
21        cur -= c
22
23    return dp[amount], used

Now you get both optimal count and one valid optimal composition.

Handle edge cases

Important cases:

  • amount 0 should return zero coins,
  • impossible amounts should return failure marker,
  • duplicate coin denominations should be normalized if needed.

Output ordering and determinism

The coin list order in reconstruction depends on loop order. If deterministic formatting is required, sort output after reconstruction or define tie-breaking logic.

Complexity

For n coins and target A, complexity is O(nA) time and O(A) space. This is efficient for moderate targets and typical interview constraints.

Common Pitfalls

  • Returning only dp[amount] without storing coin choices for reconstruction.
  • Forgetting impossible-case handling and reconstructing from invalid choice indices.
  • Confusing minimum-coin variant with count-of-ways variant.
  • Not defining tie-breaking behavior when multiple optimal combinations exist.
  • Reconstructing path without validating that each step reduces amount correctly.

Verification Workflow

Test with known examples, impossible targets, and multiple-optimal scenarios. Confirm that reconstructed coin sum equals target and coin count matches DP minimum. Add randomized regression checks where brute force is feasible for small amounts.

text
11. Validate standard sample cases
22. Validate impossible amount behavior
33. Verify reconstructed sum equals target
44. Verify reconstructed length equals dp minimum
55. Run randomized small-case cross-checks

Production Readiness Checklist

Before considering the implementation complete, run a repeatable readiness pass that validates correctness, failure handling, and operational behavior in the same environment class where this solution will run. Start with a deterministic happy-path example and then exercise one malformed input and one resource-constrained scenario. Capture structured output such as status codes, key counters, and timing metrics so regressions are visible across revisions.

Document expected behavior boundaries in plain language so future maintainers can quickly understand what is guaranteed and what is best-effort. If configuration affects behavior, include the exact setting names and safe defaults in your runbook. For team workflows, add one lightweight automated check in CI to enforce these expectations on every change and keep debugging effort low when dependencies or runtime versions change.

text
11. Validate normal input path
22. Validate malformed or missing input path
33. Validate constrained-resource behavior
44. Record timing and error metrics
55. Confirm rollback or fallback behavior
66. Add CI smoke check for regression detection

Summary

To keep track of selected coins in coin-change DP, add a choice array and reconstruct after computing minimum counts. This converts a theoretical DP result into actionable output with minimal extra complexity. With proper edge-case and reconstruction checks, the approach is robust and production-ready.


Course illustration
Course illustration

All Rights Reserved.