QA
Intermediate LevelData Structures & Algorithms

How do you solve the Coin Change problem with Dynamic Programming?

ā“ Interview Prompt: Solve Coin Change (minimum coins for target amount) using bottom-up DP, identifying the recurrence relation and state transitions.

Problem: Given coin denominations and a target amount, find the minimum number of coins to reach the target.

DP Formulation:

•
State: dp[i] = minimum coins needed to make amount i.
•
Base case: dp[0] = 0.
•
Recurrence: dp[i] = 1 + min(dp[i - coin]) for each coin ≤ i.
•
Time: $O(\text{amount} \times \text{coins})$, Space: $O(\text{amount})$.

Code Implementation Example

typescript
function coinChange(coins: number[], amount: number): number {
  const dp = new Array(amount + 1).fill(Infinity);
  dp[0] = 0;

  for (let i = 1; i <= amount; i++) {
    for (const coin of coins) {
      if (coin <= i && dp[i - coin] !== Infinity) {
        dp[i] = Math.min(dp[i], 1 + dp[i - coin]);
      }
    }
  }
  return dp[amount] === Infinity ? -1 : dp[amount];
}

console.log(coinChange([1, 5, 6, 9], 11)); // 2 (5+6)
console.log(coinChange([2], 3));            // -1
šŸ’”Coin Change bottom-up DP with recurrence dp[i] = 1 + min(dp[i-coin]).
šŸŽÆ Interview Key Takeaway

Coin Change is the archetypal unbounded knapsack DP. The recurrence dp[i] = 1 + min(dp[i - coin]) models "use 1 coin + optimal remaining".

#DSA#Dynamic Programming#Coin Change#Knapsack#Intermediate
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?