{"id":"coin-change-ii","title":"Coin Change II","difficulty":"medium","patterns":["dp-knapsack"],"primaryConcept":"dp-knapsack-counting","concepts":["dp-knapsack-counting"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft","Apple"],"category":"dynamic-programming","compareMode":"exact","executionStyle":"solution-method","syntheticTestConfig":{"inputShape":"array-scalar","primaryParam":"coins","sizeMetric":"length","constraints":["positive","distinct"],"valueRange":{"min":1,"max":100},"secondaryParams":{"amount":{"strategy":"random-int","value":{"min":0,"max":500}}}},"description":"You are given an integer `amount` and an array `coins` of distinct coin denominations.\n\nReturn the number of combinations that make up exactly `amount`.\n\nYou may use each coin denomination any number of times. Different orders of the same coins count as one combination.","examples":[{"input":"amount = 5, coins = [1, 2, 5]","output":"4","explanation":"There are four combinations: 5, 2+2+1, 2+1+1+1, and 1+1+1+1+1."},{"input":"amount = 3, coins = [2]","output":"0","explanation":"No combination of coin 2 can make amount 3."},{"input":"amount = 0, coins = [1, 2, 5]","output":"1","explanation":"There is exactly one way to make amount 0: choose no coins."}],"constraints":[{"id":"0-amount-5000","text":"0 <= amount <= 5000","check":{"kind":"valueRange","target":"amount","selector":"value","min":0,"max":5000}},{"id":"1-len-coins-300","text":"1 <= len(coins) <= 300","check":{"kind":"sizeRange","target":"coins","measure":"arrayLength","min":1,"max":300}},{"id":"1-coins-i-5000","text":"1 <= coins[i] <= 5000","check":{"kind":"valueRange","target":"coins","selector":"arrayItems","min":1,"max":5000}},{"id":"all-values-in-coins-are-distinct","text":"All values in coins are distinct","check":{"kind":"uniqueness","target":"coins","selector":"items"}},{"id":"the-answer-fits-in-a-signed-32-bit-integer","text":"The answer fits in a signed 32-bit integer","check":{"kind":"guarantee","guarantee":"resultRange","min":-2147483648,"max":2147483647}}],"starterCode":"class Solution:\n    def change(self, amount: int, coins: list[int]) -> int:\n        # Your code here\n        pass","functionName":"change","testCases":[{"id":"1","input":{"amount":5,"coins":[1,2,5]},"expected":4,"description":"Classic example with four unordered combinations."},{"id":"2","input":{"amount":3,"coins":[2]},"expected":0,"description":"Impossible amount with a single even coin."},{"id":"3","input":{"amount":10,"coins":[10]},"expected":1,"description":"One coin exactly matches the amount."},{"id":"4","input":{"amount":0,"coins":[1,2,5]},"expected":1,"description":"The empty selection is the only way to make amount zero."},{"id":"5","input":{"amount":4,"coins":[1,2,3]},"expected":4,"description":"Several overlapping choices test combination counting instead of permutation counting."},{"id":"h1","input":{"amount":7,"coins":[2,3,6,7]},"expected":2,"description":"A larger coin can be used directly, but another combination also exists."},{"id":"h2","input":{"amount":10,"coins":[1,5,10,25]},"expected":4,"description":"Common denominations with a small target."},{"id":"h3","input":{"amount":12,"coins":[2,5,3,6]},"expected":8,"description":"Coin order should not create duplicate permutations."},{"id":"h4","input":{"amount":1,"coins":[1,2,5]},"expected":1},{"id":"h5","input":{"amount":6,"coins":[1,2,3]},"expected":7},{"id":"h6","input":{"amount":0,"coins":[2,3,5]},"expected":1,"description":"The empty selection is the single way to make amount zero."},{"id":"h7","input":{"amount":7,"coins":[2,4]},"expected":0,"description":"No combination of even denominations can make an odd amount."}],"hints":[{"level":1,"content":"Think about how many ways each intermediate amount can be formed. What should `dp[0]` represent?","revealPattern":false},{"level":2,"content":"Process one coin denomination at a time. For each coin, update every reachable amount from that coin up to the target.","revealPattern":true},{"level":3,"content":"Use the transition `dp[total] += dp[total - coin]`. Iterating coins outside and totals inside counts combinations without counting different coin orders separately.","revealPattern":true}],"guidedFlow":{"version":2,"progressRevision":"coin-change-ii-2026-07-19-derived-count-table","approachSelection":{"contract":"approach-selection-v1","question":"Which approach should count combinations without counting coin order?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"recursive-enumeration","name":"Recursive Enumeration","summary":"Try every count for every coin and recursively fill the remaining amount.","decisionReason":"Enumerating every spend re-solves the same subamounts and, without a fixed coin order, counts the same combination in many orders, so it runs exponentially and overcounts.","complexity":{"time":"Exponential","space":"O(amount)"},"tradeoffs":["Runs in Exponential time and uses O(amount) space."],"isOptimal":false,"steps":["Choose how many of the first coin to use","Recurse on the remaining amount with the next coin","Repeat until the amount is zero or no coins remain","Count all successful leaves"]},{"id":"one-dimensional-dp","name":"1D Unbounded Knapsack DP","summary":"Let dp[total] store the number of combinations that make total using the coins processed so far.","decisionReason":"Processing coins one at a time is what kills the double counting: dp[total] only adds combinations using the current coin after all earlier coins are settled, so 1+2 and 2+1 collapse into one entry. One array of size amount is the whole state.","complexity":{"time":"O(amount * number of coin types)","space":"O(amount)"},"tradeoffs":["Runs in O(amount * number of coin types) time and uses O(amount) space."],"isOptimal":true,"steps":["Create a count table for amounts 0 through amount","Seed dp[0] = 1 for the empty combination","For each coin, scan totals from coin through amount","Add dp[total - coin] into dp[total]"]}]},"codingCheckpoints":[{"id":"init-dp-array","title":"Initialize the count table","description":"Create a one-dimensional table for all amounts from 0 through amount and seed one way to make amount 0.","commonMistakes":["Forgetting dp[0] = 1","Creating only amount slots instead of amount + 1"],"hint":"The empty combination makes subtotal 0 exactly once, and every other subtotal starts with zero known ways.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_count_subset_table","scope":"init-dp-array","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Allocate the counting DP table and seed the zero amount with one empty combination.","doneWhen":"This step is done when the table covers amount + 1 cells, all counts start at zero, and dp[0] is set to 1 before any coin transitions run.","shouldFailWhen":"This step should fail if the table is the wrong size, the zero base count is missing, or non-base cells start as prefilled answers.","roles":["count DP table","amount axis","empty-combination base case"],"mustProve":["The count table has one cell for each subtotal from 0 through amount.","The zero subtotal is seeded with exactly one way before processing coins."],"mustNotAccept":["A boolean reachability table in place of a count table.","A count table that never seeds dp[0]."],"equivalentVariants":["Use a list, array, or vector of zero counts with length amount + 1.","Seed the zero index to one before the nested update loop."],"proofSnippets":[{"id":"py-init-count-table-for-coin-change-ii","language":"python","code":"def change(amount, coins):\n    dp = [0] * (amount + 1)\n    dp[0] = 1"}]}},{"id":"outer-loop","title":"Process each coin denomination","description":"Loop over the coin denominations as the outer dimension so combinations are counted once.","commonMistakes":["Looping over amount first and counting permutations","Skipping a coin denomination"],"hint":"Coins should be the outer loop because each pass adds combinations that use the current coin after all previous coin types.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Drive the transition by visiting every coin denomination in a stable outer pass.","doneWhen":"This step is done when every coin denomination is scanned outside the subtotal update loop.","shouldFailWhen":"This step should fail if the solution only scans amounts, ignores the coin list, or nests the loops in a way that counts orderings as separate answers.","roles":["coin list","outer scan","combination ordering"],"mustProve":["The solution scans the available coin denominations.","The coin scan wraps the subtotal recurrence."],"mustNotAccept":["A recurrence that never iterates over the coin denominations.","A permutation-counting loop order."],"equivalentVariants":["Use a direct for-each coin loop.","Use an indexed loop over coins as long as each denomination drives a full subtotal pass."],"proofSnippets":[{"id":"py-process-each-coin-outer-loop","language":"python","code":"def change(amount, coins):\n    dp = [0] * (amount + 1)\n    dp[0] = 1\n    for total in range(1, amount + 1):\n        dp[total] = dp[total - 1]"}]}},{"id":"inner-loop","title":"Scan reachable subtotals","description":"For the current coin, scan every subtotal from coin up through amount.","commonMistakes":["Starting the subtotal loop at 0","Stopping before amount","Scanning backward for this unbounded-counting variant"],"hint":"A coin can only contribute to subtotals at least as large as itself, and scanning forward allows reuse of the same coin.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Nest a subtotal scan under each coin so each current subtotal can absorb combinations ending with that coin.","doneWhen":"This step is done when the implementation has a nested state-space scan that ranges over candidate subtotals for each coin.","shouldFailWhen":"This step should fail if there is no nested amount scan or the scan is disconnected from the DP state transition.","roles":["subtotal","current coin","nested state scan"],"mustProve":["The recurrence considers subtotals under the current coin pass.","The subtotal scan is part of the indexed DP state-space workflow."],"mustNotAccept":["A single loop that cannot combine coin choices with subtotal state.","A nested loop that is unrelated to the DP table."],"equivalentVariants":["Scan subtotals from the current coin value through the target amount.","Use an equivalent inclusive subtotal loop in another language."],"proofSnippets":[{"id":"py-scan-subtotals-for-current-coin","language":"python","code":"def change(amount, coins):\n    dp = [0] * (amount + 1)\n    dp[0] = 1\n    for coin in coins:\n        for total in range(coin, amount + 1):\n            dp[total] = dp[total - coin]"}]}},{"id":"dp-update","title":"Add ways from the reduced subtotal","description":"Update each subtotal count by adding `dp[total - coin]`.","commonMistakes":["Overwriting instead of adding","Reading dp[total + coin]","Adding a constant instead of the reduced subtotal count"],"hint":"Every way counted in `dp[total - coin]` becomes a way to make total after adding the current coin.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"applies_additive_subset_transition","scope":"dp-update","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Apply the additive count recurrence from the reduced subtotal into the current subtotal.","doneWhen":"This step is done when dp[total] is increased by dp[total - coin] inside the nested coin/subtotal scan.","shouldFailWhen":"This step should fail if the code assigns only a boolean, minimizes a cost, reads the wrong predecessor, or never adds prior counts.","roles":["current subtotal count","reduced subtotal count","additive recurrence"],"mustProve":["The update reads both the current subtotal state and the reduced subtotal state.","The update writes the sum back into the current subtotal state."],"mustNotAccept":["A min-cost transition for the fewest coins problem.","A reachability OR transition that does not count combinations."],"equivalentVariants":["Use dp[total] += dp[total - coin].","Use dp[total] = dp[total] + dp[total - coin]."],"proofSnippets":[{"id":"py-add-reduced-subtotal-count","language":"python","code":"def change(amount, coins):\n    dp = [0] * (amount + 1)\n    dp[0] = 1\n    for coin in coins:\n        for total in range(coin, amount + 1):\n            dp[total] = dp[total] + dp[total - coin]"}]}},{"id":"return-result","title":"Return the target count","description":"Return the number of combinations stored at dp[amount].","commonMistakes":["Returning the whole DP table","Returning dp[amount - 1]","Returning a boolean instead of the count"],"hint":"After all coin passes, the target cell contains the complete combination count.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Return the terminal DP count for the requested amount.","doneWhen":"This step is done when the final return reads the DP table at the amount index after all transitions are complete.","shouldFailWhen":"This step should fail if the function returns a literal, the wrong index, a boolean, or an intermediate subtotal.","roles":["target amount","terminal DP cell","answer count"],"mustProve":["The returned value comes from the same indexed DP table updated by the recurrence.","The return index is the target amount rather than a hardcoded offset."],"mustNotAccept":["Returning dp[0] or dp[amount - 1].","Returning whether the count is positive instead of the count itself."],"equivalentVariants":["Return dp[amount] directly.","Store dp[amount] in a local answer variable and return that value."],"proofSnippets":[{"id":"py-return-target-count","language":"python","code":"def change(amount, coins):\n    dp = [0] * (amount + 1)\n    dp[0] = 1\n    for coin in coins:\n        for total in range(coin, amount + 1):\n            dp[total] = dp[total] + dp[total - coin]\n    return dp[amount]"}]}}],"slides":[{"id":"read-the-signal","chapter":"What we're counting","kind":"info","eyebrow":"Read the problem","title":"Count the combinations that hit the amount","workspacePanel":"problem","body":["You get coin values and a target amount. Using any number of each coin, count how many distinct combinations add up to exactly the amount.","A combination is a multiset: 2+1+1 and 1+2+1 are the same combination, counted once. The safe starting move is to enumerate every way to spend coins. Watch what that counts."]},{"id":"brute-force","chapter":"The double-count","kind":"code-trace","eyebrow":"The obvious way","title":"Spend a coin, then count the rest","summary":"Spending a coin and recursing on the rest reaches amount 0 down every path, and each path that lands there is one finished way. Watch which ways it ends up counting more than once.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def count(amount: int, coins: list[int]) -> int:\n    if amount == 0:\n        return 1\n    ways = 0\n    for coin in coins:\n        if coin <= amount:\n            ways += count(amount - coin, coins)\n    return ways","steps":[{"id":"fork","title":"Amount 3 forks by coin","codeLine":5,"summary":"With coins [1, 2], amount 3 spends a 1 and solves 2, or spends a 2 and solves 1. Each branch keeps spending until it hits 0.","state":{"tree":[3,2,1,1,0,0,null,0],"node":0}},{"id":"two-leaves","title":"The same coins, reached two ways","codeLine":7,"summary":"Spending 1 then 2 lands on amount 0; spending 2 then 1 lands on amount 0 as well. Both leaves are the single combination 1+2.","state":{"tree":[3,2,1,1,0,0,null,0],"swapped":[4,5]}},{"id":"overcount","title":"It returns 3, not 2","codeLine":8,"summary":"count(3) tallies 1+1+1, 1+2, and 2+1 as three leaves. But 1+2 and 2+1 are one combination, so the true answer is 2.","state":{"tree":[3,2,1,1,0,0,null,0],"visited":[0],"swapped":[4,5]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (amount === 0) {\n    return 1;\n}\nlet ways = 0;\nfor (const coin of coins) {\n    if (coin <= amount) {\n        ways += count((amount - coin), coins);\n    }\n}\nreturn ways;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":7,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (amount === 0) {\n    return 1;\n}\nlet ways = 0;\nfor (const coin of coins) {\n    if (coin <= amount) {\n        ways += count((amount - coin), coins);\n    }\n}\nreturn ways;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":7,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (amount == 0) {\n    return 1;\n}\nint ways = 0;\nforeach (int coin in coins) {\n    if (coin <= amount) {\n        ways += Count(amount - coin, coins);\n    }\n}\nreturn ways;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":7,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if (amount == 0) {\n    return 1;\n}\nint ways = 0;\nfor (int coin : coins) {\n    if (coin <= amount) {\n        ways += count((amount - coin), coins);\n    }\n}\nreturn ways;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":7,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (amount == 0) {\n    return 1;\n}\nint ways = 0;\nfor (Integer coin : coins) {\n    if (coin <= amount) {\n        ways += count((amount - coin), coins);\n    }\n}\nreturn ways;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":7,"endLine":9}}}}},"body":["For each amount, spend each coin in turn and add up the ways to finish the rest."]},{"id":"double-count","chapter":"The double-count","kind":"case-probe","eyebrow":"Name the waste","title":"Why does this overcount the combinations?","workspacePanel":"trace","options":[{"id":"order","label":"It counts the same coins in different orders as separate ways","rationale":"Spending 1 then 2 and spending 2 then 1 reach amount 0 down separate branches, so the one combination 1+2 is tallied twice.","isCorrect":true},{"id":"recompute","label":"It recomputes amount 1 more than once","rationale":"Re-solving a subamount wastes time, but caching it would still tally 1+2 and 2+1 separately. The overcount is about order, not speed.","isCorrect":false},{"id":"base","label":"Returning 1 at amount 0 is wrong","rationale":"Reaching amount 0 really is one finished combination. The error is letting both orderings of the same coins reach it.","isCorrect":false}],"answer":"It treats order as meaningful: 1+2 and 2+1 finish on different branches and get counted twice, so the tally runs high.","summary":"For amount 3 with coins [1, 2], it returns 3, but only two combinations exist."},{"id":"fix-the-order","chapter":"The rule","kind":"case-probe","eyebrow":"Build the rule","title":"How do you count each combination exactly once?","summary":"For amount 5 with coins [1, 2, 5], the same multiset can be reached in several spend orders.","workspacePanel":"visualizer","options":[{"id":"coin-at-a-time","label":"Settle every amount using only coin 1, then layer coin 2 on top, then coin 5","rationale":"Bringing in one coin denomination at a time, and never going back to an earlier coin, fixes a single order for each multiset. 1+2 is counted when coin 2 is added; 2+1 never gets a second chance.","isCorrect":true},{"id":"sort-paths","label":"Enumerate every order, then divide out the duplicates","rationale":"Counting all orderings and correcting afterward needs the duplicate count per multiset, which varies by how many coins repeat. There is no single divisor.","isCorrect":false},{"id":"sort-coins","label":"Sort the coin list before enumerating","rationale":"Sorting changes which coin is tried first but still lets a branch spend a small coin after a large one, so 1+2 and 2+1 both survive.","isCorrect":false}],"answer":"Process one coin denomination at a time across all amounts, and never revisit an earlier coin. That pins a single order per multiset, so each combination is counted once.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"fix-order-state","state":{"nums":[1,2,5],"i":0,"labels":{"nums":"coins","i":"coin"}}}]}},{"id":"state-meaning","kind":"case-probe","chapter":"The rule","eyebrow":"Define the table","title":"After coins 1 and 2 finish, the amount-4 cell holds 3. What should that 3 mean?","summary":"The three combinations visible so far are 1+1+1+1, 2+1+1, and 2+2. Coin 5 has not been processed yet.","workspacePanel":"trace","options":[{"id":"processed-combinations","label":"Combinations that make amount using coins already processed","rationale":"After a coin finishes its sweep, each slot counts combinations built only from coins up through that denomination.","isCorrect":true},{"id":"ordered-sequences","label":"Different orders of the same coins that make amount","rationale":"The coin-by-coin sweep is chosen to avoid counting the same multiset in several orders."},{"id":"remaining-amount","label":"How much amount is still unpaid after one path","rationale":"The index already is the amount being formed. The value in the slot is a count of combinations."}],"answer":"dp[amount] counts combinations that make that amount using only the coins whose sweeps have already run. That meaning preserves the fixed denomination order that removed the duplicates."},{"id":"base-case","chapter":"The rule","kind":"case-probe","eyebrow":"Set the floor","title":"Coin 5 should create one way to make 5. What must the empty starting state say?","summary":"Before any coin runs, the table holds the counts every later sweep will read from.","workspacePanel":"visualizer","options":[{"id":"one-and-zero","label":"Amount 0 holds 1; every other amount starts at 0","rationale":"The empty selection is one combination of amount 0. A coin that lands on the target then reads that 1 from dp[0] and counts itself once; unsolved amounts start with no ways.","isCorrect":true},{"id":"all-zero","label":"Every amount, including 0, starts at 0","rationale":"Then a coin landing on the target adds dp[0] = 0 and contributes nothing, so that combination is never counted. Amount 0 must start at 1.","isCorrect":false},{"id":"all-one","label":"Every amount starts at 1","rationale":"No amount above 0 has a known combination before the coins run. Seeding them at 1 invents ways the sweeps never justified.","isCorrect":false}],"answer":"dp[0] = 1 for the empty combination, and every larger amount starts at 0. A coin that reaches the target adds that single base way.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"base-state","state":{"nums":["?",0,0,0,0,0],"i":0,"labels":{"nums":"dp","i":"total"}}}]}},{"id":"recurrence","chapter":"The rule","kind":"case-probe","eyebrow":"Build the rule","title":"dp[5] already has 1 way. Coin 2 can extend 2 ways from amount 3. What should dp[5] become?","summary":"The single way already recorded for amount 5 is five 1-coins.","workspacePanel":"visualizer","options":[{"id":"add-reduced","label":"3: keep the old way and add the two extensions","rationale":"Every way counted in `dp[total - coin]` becomes a way to make total by adding one of this coin. So `dp[total]` gains `dp[total - coin]`, keeping the ways found with earlier coins.","isCorrect":true},{"id":"overwrite","label":"2: replace the old count with the two extensions","rationale":"Replacing discards the combinations that did not use this coin. The new ways add to the old ones, they do not overwrite them.","isCorrect":false},{"id":"add-prev-total","label":"4: add the three ways from amount 4","rationale":"That assumes a 1-coin step. Here `dp[total - 1]` points to total 4, holding 3, while `dp[total - coin]` points to total 3, holding 2. The current coin is 2, so the reachable predecessor is dp[3] = 2, not dp[4] = 3.","isCorrect":false}],"answer":"`dp[total] += dp[total - coin]`: every combination counted in `dp[total - coin]` becomes one that makes total by adding this coin, stacked on the counts earlier coins already left.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"recurrence-state","state":{"nums":[1,1,2,2,3,1],"i":5,"labels":{"nums":"dp","i":"total"}}}]}},{"id":"approach-selection","chapter":"The rule","kind":"choice","source":"approach-selection","eyebrow":"Name what you built","title":"Which representation matches the rule we just derived?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"nums":[1,1,2,2,3,4],"labels":{"nums":"ways by amount"}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"One coin sweeps the table, then the next","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[1,0,0,0,0,0],"i":0,"labels":{"nums":"dp","i":"total"}}}]},"body":["The table starts with amount 0 at one way and every other amount at zero ways.","Take the coins one at a time. For the current coin, sweep totals from the coin value up to the target, and add into each total the ways already counted for total minus the coin.","Because each coin finishes its sweep before the next begins, every multiset is counted in exactly one order. With coins [1, 2, 5] and amount 5, the table should land on 4."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the table","title":"Trace the coin sweeps","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-coin-1","state":{"nums":[1,1,1,1,1,1],"i":5,"labels":{"nums":"dp","i":"total"}}},{"id":"after-coin-2","state":{"nums":[1,1,2,2,3,3],"i":4,"labels":{"nums":"dp","i":"total"}}},{"id":"after-coin-5","state":{"nums":[1,1,2,2,3,4],"i":5,"labels":{"nums":"dp","i":"total"}}}]},"beats":[{"id":"after-coin-1","title":"After coin 1 sweeps, what is dp[5]?","summary":"Only coin 1 has run. dp starts as 1 at amount 0 and 0 everywhere else.","prompt":"The sweep for coin 1 has finished across totals 1 through 5.","options":[{"id":"one","label":"1","rationale":"Each total added dp[total - 1], carrying the single all-1s way upward. The only combination of amount 5 so far is 1+1+1+1+1.","isCorrect":true},{"id":"five","label":"5","rationale":"There are five coins in that combination, but it is still one combination. dp counts combinations, not coins, so dp[5] is 1.","isCorrect":false},{"id":"zero","label":"0","rationale":"Amount 5 is reachable with five 1-coins, so its count is not 0. Each sweep carried dp[0] = 1 forward to dp[5].","isCorrect":false}],"answer":"1. Coin 1 carries the single 1+1+1+1+1 combination up to dp[5]."},{"id":"after-coin-2","title":"After coin 2 sweeps, why is dp[4] now 3?","summary":"Before this sweep every dp entry was 1. Coin 2 adds dp[total - 2] into each total from 2 up.","prompt":"The sweep for coin 2 has reached total 4.","options":[{"id":"three-combos","label":"Three combinations now make 4: 1+1+1+1, 2+1+1, and 2+2","rationale":"dp[4] started at 1 (all 1s) and gained dp[2], which is now 2 (1+1 and 2). Those add to 3, exactly the three multisets.","isCorrect":true},{"id":"permutations","label":"The orderings of one and two coins reaching 4 are counted","rationale":"Order never enters: coin 2 finishes its own sweep, so 2+1+1 and 1+2+1 are the same single combination here, not separate ones.","isCorrect":false},{"id":"reset","label":"dp[4] was reset to dp[2] = 2","rationale":"The sweep adds rather than replaces, so the all-1s combination already counted is kept. 1 + 2 gives 3, not 2.","isCorrect":false}],"answer":"dp[4] = 1 + dp[2] = 1 + 2 = 3: the all-1s way plus the two ways (1+1 and 2) that gain a coin 2."},{"id":"after-coin-5","title":"After coin 5 sweeps, what is the answer at dp[5]?","summary":"Before this sweep dp[5] held 3. Coin 5 sweeps only total 5, adding dp[0].","prompt":"The sweep for coin 5 reaches total 5, the target.","options":[{"id":"four","label":"4, the final dp[5] count","rationale":"dp[5] was 3 from coins 1 and 2, then gained dp[0] = 1 for the single 5-coin. 3 + 1 = 4, the final answer.","isCorrect":true},{"id":"three","label":"3, unchanged","rationale":"Coin 5 lands exactly on the target and reads dp[0] = 1, so dp[5] must rise to 4. It does not stay at 3.","isCorrect":false},{"id":"five","label":"5","rationale":"Only one new combination, the single 5-coin, is added. dp[5] goes from 3 to 4, not 5.","isCorrect":false}],"answer":"4. dp[5] = 3 + dp[0] = 3 + 1, picking up the single 5-coin combination, and that is what the function returns."}]},{"id":"loop-order-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could the amount loop sit on the outside instead?","summary":"Sweeping each total and trying every coin inside looks like the same two loops in the other order, and it still fills the table left to right. But finishing a total before any coin is done lets one multiset arrive in several orders, and the overcount grows as the amount does. Watch it on amount 4.","workspacePanel":"trace","pitfall":"The table below loops amount on the outside and coins on the inside.","whyItMatters":"With coins [1, 2] and amount 4 the answer is 3: 1+1+1+1, 2+1+1, and 2+2. But totals-outside returns 5, because every total reads predecessors that already mixed both coins, so each ordering is recounted and the gap widens with the amount, not by a fixed one. Keep coins on the outside so each denomination finishes one full sweep before the next, pinning one order per combination.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"dp = [0] * (amount + 1)\ndp[0] = 1\nfor total in range(1, amount + 1):\n    for coin in coins:\n        if coin <= total:\n            dp[total] = dp[total] + dp[total - coin]\nreturn dp[amount]","steps":[{"id":"total-2","title":"Total 2 reaches 2, still correct","codeLine":6,"summary":"coins = [1, 2], amount = 4. At total 2, coin 1 adds dp[1] = 1 and coin 2 adds dp[0] = 1, so dp[2] = 2. Both true: 1+1 and 2.","state":{"nums":[1,1,2,0,0],"i":2,"labels":{"nums":"dp","i":"total"}}},{"id":"total-3-enter","title":"The total loop reaches 3","codeLine":3,"summary":"Now total is 3, and every coin is tried again here. dp[2] already mixed both coins, so the predecessors this total reads are no longer order-free.","state":{"nums":[1,1,2,0,0],"i":3,"labels":{"nums":"dp","i":"total"}}},{"id":"total-3-creeps","title":"Total 3 adds dp[2] and dp[1]","codeLine":6,"summary":"Coin 1 adds dp[2] = 2 and coin 2 adds dp[1] = 1, so dp[3] = 3. The true count for 3 is 2 (1+1+1 and 2+1), so the overcount has already started.","state":{"nums":[1,1,2,3,0],"i":3,"labels":{"nums":"dp","i":"total"}}},{"id":"total-4-enter","title":"The total loop reaches 4","codeLine":3,"summary":"total is now 4, the target. Its predecessors dp[3] = 3 and dp[2] = 2 already carry the inflated counts from earlier totals.","state":{"nums":[1,1,2,3,0],"i":4,"labels":{"nums":"dp","i":"total"}}},{"id":"total-4-blowup","title":"Total 4 inflates to 5, not 3","codeLine":6,"summary":"Coin 1 adds dp[3] = 3 and coin 2 adds dp[2] = 2, so dp[4] = 5. The real answer is 3, and the gap is now two, wider than the one-off seen at total 3.","state":{"nums":[1,1,2,3,5],"i":4,"labels":{"nums":"dp","i":"total"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const dp = Array((amount + 1)).fill(0);\ndp[0] = 1;\nfor (let total = 1; total < (amount + 1); total++) {\n    for (const coin of coins) {\n        if (coin <= total) {\n            dp[total] = (dp[total] + dp[(total - coin)]);\n        }\n    }\n}\nreturn dp[amount];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const dp = Array((amount + 1)).fill(0);\ndp[0] = 1;\nfor (let total = 1; total < (amount + 1); total++) {\n    for (const coin of coins) {\n        if (coin <= total) {\n            dp[total] = (dp[total] + dp[(total - coin)]);\n        }\n    }\n}\nreturn dp[amount];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int[] dp = new int[(amount + 1)];\ndp[0] = 1;\nfor (int total = 1; total < (amount + 1); total++) {\n    for (Integer coin : coins) {\n        if (coin <= total) {\n            dp[total] = (dp[total] + dp[(total - coin)]);\n        }\n    }\n}\nreturn dp[amount];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> dp = Enumerable.Repeat<int>(0, amount + 1).ToList();\ndp[0] = 1;\nfor (int total = 1; total < amount + 1; total++) {\n    foreach (int coin in coins) {\n        if (coin <= total) {\n            dp[total] = dp[total] + dp[total - coin];\n        }\n    }\n}\nreturn dp[amount];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> dp = vector<int>((amount + 1), 0);\ndp[0] = 1;\nfor (int total = 1; total < (amount + 1); total++) {\n    for (int coin : coins) {\n        if (coin <= total) {\n            dp[total] = (dp[total] + dp[(total - coin)]);\n        }\n    }\n}\nreturn dp[amount];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Counting each combination once came from finishing one coin sweep before the next, with dp[0] seeded at one empty way.","Two inputs lean hardest on that base case: an amount no combination of coins can reach, and an amount of zero that the whole table reads from."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[1,0,0,0,0,0],"i":0,"labels":{"nums":"dp","i":"total"}}}]}},{"id":"unreachable-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if no combination of coins reaches the amount?","summary":"coins = [2], amount = 3.","workspacePanel":"visualizer","options":[{"id":"zero","label":"0, because no sweep ever adds a real way to dp[3]","rationale":"Coin 2 reaches total 3 but adds dp[1], which is 0, so nothing lands a way on dp[3]. It keeps its starting count of 0.","isCorrect":true},{"id":"minus-one","label":"-1, since the amount is impossible","rationale":"This problem reports a count of combinations, never -1. An impossible amount simply has 0 combinations.","isCorrect":false},{"id":"one","label":"1, the nearest single coin","rationale":"A single 2-coin makes 2, not 3, and no combination of 2s is odd. dp[3] stays at 0.","isCorrect":false}],"answer":"0. Coin 2 reaches total 3 but reads dp[1] = 0, so dp[3] gains nothing and stays at its starting 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"unreachable-state","state":{"nums":[1,0,1,0],"i":3,"labels":{"nums":"dp","i":"total"}}}]}},{"id":"zero-amount-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"How many combinations make an amount of 0?","summary":"coins = [1, 2, 5], amount = 0.","workspacePanel":"visualizer","options":[{"id":"one","label":"1, the empty combination","rationale":"Choosing no coins is the one way to total 0. That is exactly the dp[0] = 1 seed every larger amount builds on.","isCorrect":true},{"id":"zero","label":"0, since no coins are used","rationale":"Using no coins is itself one valid combination. The count is 1.","isCorrect":false},{"id":"three","label":"3, one per coin","rationale":"The coins do not each make 0 on their own; the only way to total 0 is to pick none. The count is 1.","isCorrect":false}],"answer":"1. The empty selection is the single combination that totals 0, which is why dp[0] is seeded at 1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"zero-amount-state","state":{"nums":[1],"i":0,"labels":{"nums":"dp","i":"total"}}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Coins sweep on the outside, totals on the inside, so each combination is counted once.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[1,0,0,0,0,0],"i":0,"labels":{"nums":"dp","i":"total"}}}]},"body":["Make a count table sized to the amount, all zeros except amount 0 seeded at one empty combination. Take each coin in turn, sweep totals from the coin value up to the target, and add into each total the ways already counted for total minus the coin. Read the answer off the target cell."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the combination-count table","summary":"Now turn the sweep into code: size the table and seed dp[0] = 1, loop the coins on the outside, scan totals from the coin up to the target, add dp[total - coin] into each total, then read off dp[amount].","workspacePanel":"code","checkpoints":[{"id":"init-dp-array","title":"Initialize the count table","description":"Create a one-dimensional table for all amounts from 0 through amount and seed one way to make amount 0.","commonMistakes":["Forgetting dp[0] = 1","Creating only amount slots instead of amount + 1"],"hint":"The empty combination makes subtotal 0 exactly once, and every other subtotal starts with zero known ways.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_count_subset_table","scope":"init-dp-array","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Allocate the counting DP table and seed the zero amount with one empty combination.","doneWhen":"This step is done when the table covers amount + 1 cells, all counts start at zero, and dp[0] is set to 1 before any coin transitions run.","shouldFailWhen":"This step should fail if the table is the wrong size, the zero base count is missing, or non-base cells start as prefilled answers.","roles":["count DP table","amount axis","empty-combination base case"],"mustProve":["The count table has one cell for each subtotal from 0 through amount.","The zero subtotal is seeded with exactly one way before processing coins."],"mustNotAccept":["A boolean reachability table in place of a count table.","A count table that never seeds dp[0]."],"equivalentVariants":["Use a list, array, or vector of zero counts with length amount + 1.","Seed the zero index to one before the nested update loop."],"proofSnippets":[{"id":"py-init-count-table-for-coin-change-ii","language":"python","code":"def change(amount, coins):\n    dp = [0] * (amount + 1)\n    dp[0] = 1"}]}},{"id":"outer-loop","title":"Process each coin denomination","description":"Loop over the coin denominations as the outer dimension so combinations are counted once.","commonMistakes":["Looping over amount first and counting permutations","Skipping a coin denomination"],"hint":"Coins should be the outer loop because each pass adds combinations that use the current coin after all previous coin types.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Drive the transition by visiting every coin denomination in a stable outer pass.","doneWhen":"This step is done when every coin denomination is scanned outside the subtotal update loop.","shouldFailWhen":"This step should fail if the solution only scans amounts, ignores the coin list, or nests the loops in a way that counts orderings as separate answers.","roles":["coin list","outer scan","combination ordering"],"mustProve":["The solution scans the available coin denominations.","The coin scan wraps the subtotal recurrence."],"mustNotAccept":["A recurrence that never iterates over the coin denominations.","A permutation-counting loop order."],"equivalentVariants":["Use a direct for-each coin loop.","Use an indexed loop over coins as long as each denomination drives a full subtotal pass."],"proofSnippets":[{"id":"py-process-each-coin-outer-loop","language":"python","code":"def change(amount, coins):\n    dp = [0] * (amount + 1)\n    dp[0] = 1\n    for total in range(1, amount + 1):\n        dp[total] = dp[total - 1]"}]}},{"id":"inner-loop","title":"Scan reachable subtotals","description":"For the current coin, scan every subtotal from coin up through amount.","commonMistakes":["Starting the subtotal loop at 0","Stopping before amount","Scanning backward for this unbounded-counting variant"],"hint":"A coin can only contribute to subtotals at least as large as itself, and scanning forward allows reuse of the same coin.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Nest a subtotal scan under each coin so each current subtotal can absorb combinations ending with that coin.","doneWhen":"This step is done when the implementation has a nested state-space scan that ranges over candidate subtotals for each coin.","shouldFailWhen":"This step should fail if there is no nested amount scan or the scan is disconnected from the DP state transition.","roles":["subtotal","current coin","nested state scan"],"mustProve":["The recurrence considers subtotals under the current coin pass.","The subtotal scan is part of the indexed DP state-space workflow."],"mustNotAccept":["A single loop that cannot combine coin choices with subtotal state.","A nested loop that is unrelated to the DP table."],"equivalentVariants":["Scan subtotals from the current coin value through the target amount.","Use an equivalent inclusive subtotal loop in another language."],"proofSnippets":[{"id":"py-scan-subtotals-for-current-coin","language":"python","code":"def change(amount, coins):\n    dp = [0] * (amount + 1)\n    dp[0] = 1\n    for coin in coins:\n        for total in range(coin, amount + 1):\n            dp[total] = dp[total - coin]"}]}},{"id":"dp-update","title":"Add ways from the reduced subtotal","description":"Update each subtotal count by adding `dp[total - coin]`.","commonMistakes":["Overwriting instead of adding","Reading dp[total + coin]","Adding a constant instead of the reduced subtotal count"],"hint":"Every way counted in `dp[total - coin]` becomes a way to make total after adding the current coin.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"applies_additive_subset_transition","scope":"dp-update","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Apply the additive count recurrence from the reduced subtotal into the current subtotal.","doneWhen":"This step is done when dp[total] is increased by dp[total - coin] inside the nested coin/subtotal scan.","shouldFailWhen":"This step should fail if the code assigns only a boolean, minimizes a cost, reads the wrong predecessor, or never adds prior counts.","roles":["current subtotal count","reduced subtotal count","additive recurrence"],"mustProve":["The update reads both the current subtotal state and the reduced subtotal state.","The update writes the sum back into the current subtotal state."],"mustNotAccept":["A min-cost transition for the fewest coins problem.","A reachability OR transition that does not count combinations."],"equivalentVariants":["Use dp[total] += dp[total - coin].","Use dp[total] = dp[total] + dp[total - coin]."],"proofSnippets":[{"id":"py-add-reduced-subtotal-count","language":"python","code":"def change(amount, coins):\n    dp = [0] * (amount + 1)\n    dp[0] = 1\n    for coin in coins:\n        for total in range(coin, amount + 1):\n            dp[total] = dp[total] + dp[total - coin]"}]}},{"id":"return-result","title":"Return the target count","description":"Return the number of combinations stored at dp[amount].","commonMistakes":["Returning the whole DP table","Returning dp[amount - 1]","Returning a boolean instead of the count"],"hint":"After all coin passes, the target cell contains the complete combination count.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Return the terminal DP count for the requested amount.","doneWhen":"This step is done when the final return reads the DP table at the amount index after all transitions are complete.","shouldFailWhen":"This step should fail if the function returns a literal, the wrong index, a boolean, or an intermediate subtotal.","roles":["target amount","terminal DP cell","answer count"],"mustProve":["The returned value comes from the same indexed DP table updated by the recurrence.","The return index is the target amount rather than a hardcoded offset."],"mustNotAccept":["Returning dp[0] or dp[amount - 1].","Returning whether the count is positive instead of the count itself."],"equivalentVariants":["Return dp[amount] directly.","Store dp[amount] in a local answer variable and return that value."],"proofSnippets":[{"id":"py-return-target-count","language":"python","code":"def change(amount, coins):\n    dp = [0] * (amount + 1)\n    dp[0] = 1\n    for coin in coins:\n        for total in range(coin, amount + 1):\n            dp[total] = dp[total] + dp[total - coin]\n    return dp[amount]"}]}}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Each combination is counted once because each coin finishes its sweep before the next coin starts.","workspacePanel":"code","body":["Seed amount 0 at one empty combination, then bring in one coin at a time, sweeping totals upward and adding dp[total - coin] into dp[total].","Keeping coins on the outside fixes one order per multiset, so 1+2 and 2+1 are the same single combination."],"takeaways":[{"title":"Coins outside, totals inside","body":"Finishing each coin sweep before the next pins one order per combination, which is what turns permutation counting into combination counting."},{"title":"Amount zero anchors it","body":"dp[0] = 1 is the empty combination every transition reads from, so a coin landing on the target counts itself exactly once."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
