Start learning free

LESSON 245 OF 314 · DYNAMIC PROGRAMMING

Coin Change in TypeScript: O(n · amount) Bottom-Up DP

Practice O(n · amount) Read the full explanation

You get an array coins of coin values and an integer amount.

Return the smallest number of coins that add up to exactly amount.

You can use each coin value as many times as you like. If no mix of coins makes amount, return -1.

 

Example 1:

Input: coins = [2, 5, 10], amount = 27
Output: 4
Explanation: 27 = 10 + 10 + 5 + 2.
No three coins add up to 27.

Example 2:

Input: coins = [4, 6], amount = 9
Output: -1
Explanation: Both coin values are even.
So every sum of them is even.
9 is odd, so no mix of coins makes it.

Example 3:

Input: coins = [1, 5, 6, 9], amount = 11
Output: 2
Explanation: 11 = 5 + 6.
9 + 1 + 1 also makes 11, but that is three coins.

 

Constraints:

  • coins holds 1 to 12 values.
  • Each value is from 1 to 231 - 1.
  • amount is from 0 to 10,000.
  • For amount = 0, the answer is 0 (no coins are needed).
STEP 1 OF 8
    Ctrl + Enter to check

    TYPESCRIPT · DYNAMIC PROGRAMMING

    Coin Change in TypeScript, explained

    Problem overview

    The method coinChange(coins: number[], amount: number): number receives the available coin values and a target sum. Each value can be used as many times as needed. It returns the fewest coins that add up to exactly amount, or -1 if no combination does. When amount is 0 the answer is 0.

    With coins = [1, 2, 5] and amount = 11 the answer is 3, from 5 + 5 + 1. With coins = [2] and amount = 3 the answer is -1, since 2s only make even sums.

    Approach: the fewest coins for every sum up to amount

    The tempting shortcut is to take the largest coin that fits, again and again. It fails on coins = [1, 3, 4] and amount = 6: the greedy way gives 4 + 1 + 1, three coins, while 3 + 3 needs only two.

    The reliable method is to answer the question for every sum from 0 to amount. Let dp[i] be the fewest coins that make the sum i. If the last coin added is coin, the coins before it make i - coin, so the total is dp[i - coin] + 1. Trying every coin as the last one and keeping the smallest result gives dp[i]. Each entry reuses answers for smaller sums, which is the dynamic programming.

    A sum that can't be made needs a marker. Every coin is worth at least 1, so no sum i ever needs more than i coins. A count of amount + 1 can never be a real answer, so the table starts with that value everywhere, as a stand-in for "not reachable yet".

    Step by step

    1. Create dp as a number[] with amount + 1 entries, all set to amount + 1.
    2. Set dp[0] = 0. The sum 0 takes no coins, and every other sum is built on top of it.
    3. Loop over the sums with i from 1 up to and including amount. By the time i is reached, all smaller sums are final.
    4. Loop over the coins with for...of. Each coin is tried as the last one added to make i.
    5. Skip coins that don't fit. The check coin <= i avoids a negative index i - coin.
    6. Update with Math.min: dp[i] becomes the smaller of its current value and dp[i - coin] + 1. If i - coin can't be made, dp[i - coin] + 1 is more than amount, so it never looks like a real answer.
    7. Return -1 if dp[amount] is still greater than amount: no combination reached it.
    8. Otherwise return dp[amount].

    The table for coins = [1, 3, 4] and amount = 6, as it looks after each value of i:

    start  [7,7,7,7,7,7,7]
    dp[0]  [0,7,7,7,7,7,7]
    i=1    [0,1,7,7,7,7,7]
    i=2    [0,1,2,7,7,7,7]
    i=3    [0,1,2,1,7,7,7]
    i=4    [0,1,2,1,1,7,7]
    i=5    [0,1,2,1,1,2,7]
    i=6    [0,1,2,1,1,2,2]

    For i = 6 the coin 1 gives dp[5] + 1 = 3, the coin 3 gives dp[3] + 1 = 2, and the coin 4 gives dp[2] + 1 = 3. The smallest is 2, so the function returns 2.

    The solution in TypeScript

    class Solution {
        coinChange(coins: number[], amount: number): number {
            const dp: number[] = new Array(amount + 1).fill(amount + 1);
            dp[0] = 0;
            for (let i = 1; i <= amount; i++) {
                for (const coin of coins) {
                    if (coin <= i) {
                        dp[i] = Math.min(dp[i], dp[i - coin] + 1);
                    }
                }
            }
            if (dp[amount] > amount) return -1;
            return dp[amount];
        }
    }
    

    The TypeScript details worth knowing:

    • new Array(amount + 1).fill(amount + 1). new Array(k) with one number creates an array of k empty slots, and fill writes the same value into all of them. new Array(3).fill(3) gives [3, 3, 3]. The declared type number[] is only for the compiler: it is erased when the code becomes JavaScript.
    • for...of over an array gives the values themselves, not the indices, which is what coin needs. for...in would give the indices as strings.
    • Numbers are doubles. The sums here stay small, but a coin value can be as large as 2147483647. For coins = [2147483647] and amount = 10000, the check coin <= i is false every time, so the table is never updated and the function returns -1. No integer overflow can happen, because nothing is added to such a coin.
    • The second if has no braces. if (dp[amount] > amount) return -1; is a single statement on one line, which is valid and common for guard clauses.

    Complexity

    Time: O(n · amount), where n is the number of coins. The outer loop runs amount times and the inner loop runs n times, with constant work inside. With at most 12 coins and an amount up to 10,000, that is at most about 120,000 steps.

    Space: O(amount), for the table of amount + 1 numbers.

    Edge cases and common mistakes

    • amount = 0. The table has one entry, dp[0] = 0, and the loops don't run. The function returns 0, which is the right answer: no coins at all.
    • No combination. [2] with amount 3 returns -1. So does [5] with amount 3, where the only coin is bigger than the target.
    • Using greedy. It returns 3 for [1, 3, 4] and 6, not 2.
    • Starting the table with 0 instead of amount + 1. Math.min would then never find anything smaller, and unreachable sums would look like they take no coins.
    • Starting the table with Infinity. This also works in JavaScript, since Infinity + 1 is Infinity, but the answer check would then have to compare with Infinity. The lesson uses amount + 1, which keeps every entry a normal number.
    • Dropping the coin <= i check. The index i - coin would be negative. In JavaScript, dp[-1] is undefined, and undefined + 1 is NaN. Math.min then returns NaN and corrupts the table.
    • Looping up to i < amount. The last sum, amount itself, would never be computed.

    Testing

    • coins = [1, 2, 5], amount = 11 gives 3.
    • coins = [2], amount = 3 gives -1.
    • coins = [1, 3, 4], amount = 6 gives 2.
    • coins = [1], amount = 0 gives 0.
    • coins = [5], amount = 3 gives -1.
    • coins = [2, 5], amount = 7 gives 2.
    • coins = [186, 419, 83, 408], amount = 6249 gives 20.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free