Coin Change - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

Problem

Given coin denominations coins and a target amount, find the minimum number of coins needed to make up the amount. If it’s impossible, return -1.

DP Definition & Initialization

We’ll use a Dynamic Programming (DP) array where dp[i] stores the minimum number of coins needed to make amount i.

  • Initialize dp with size amount + 1, filling it with Infinity to represent amounts that are initially unreachable.
  • Set the base case: dp[0] = 0, since no coins are needed to make amount 0.

Transition & Loop Structure

  1. For each coin coin in coins (outer loop):
    • For each target amount currentAmount from coin up to amount (inclusive), check whether using this coin can reduce the number of coins needed for currentAmount.
    • πŸ’‘ Idea: If the smaller amount (currentAmount βˆ’ coin) is reachable using the coins encountered so far, then we can form currentAmount by adding one more coin. Formally:
      dp[currentAmount] = min(dp[currentAmount], dp[currentAmount βˆ’ coin] + 1)
    • Because we traverse currentAmount in increasing order (from coin to amount), the sub-amount (currentAmount βˆ’ coin) has already been processed utilizing the current coin. This naturally allows multiple uses of this coin - for example, with coin = 5, dp[11] can build upon dp[6], which was already processed utilizing this same coin (5), effectively adding another 5 to reach 11..

Result

  • If dp[amount] === Infinity, it’s impossible β†’ return -1.
  • Otherwise, return dp[amount] β€” the fewest coins needed to reach the target.

Time Complexity

O(n Γ— amount) β€” where n is the number of available coins.

The algorithm iterates once for each coin, scanning all possible currentAmount values from coin up to amount. Therefore, the total number of iterations is proportional to n Γ— amount.

Space Complexity

O(amount) β€” only the DP table is stored.

We maintain a one-dimensional DP array dp of size amount + 1, where each entry dp[i] stores the fewest coins needed to make amount i.

Visucodize editorial solution titled JS Solution for LeetCode's Coin Change coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/coin-change.