Challenge - 5 Problems
Coin Change Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Coin Change Ways Calculation
What is the output of the following JavaScript code that calculates the total number of ways to make change for amount 5 using coins [1, 2, 5]?
DSA Javascript
function coinChangeWays(coins, amount) {
const dp = Array(amount + 1).fill(0);
dp[0] = 1;
for (const coin of coins) {
for (let i = coin; i <= amount; i++) {
dp[i] += dp[i - coin];
}
}
return dp[amount];
}
console.log(coinChangeWays([1, 2, 5], 5));Attempts:
2 left
💡 Hint
Think about how many combinations of coins can sum to 5 using 1, 2, and 5.
✗ Incorrect
The code uses dynamic programming to count ways. For amount 5 with coins [1,2,5], the ways are: {1+1+1+1+1}, {1+1+1+2}, {1+2+2}, {5}, totaling 4 ways.
❓ Predict Output
intermediateResult of Coin Change with Different Coins
What does this code print for amount 4 with coins [1, 3, 4]?
DSA Javascript
function coinChangeWays(coins, amount) {
const dp = Array(amount + 1).fill(0);
dp[0] = 1;
for (const coin of coins) {
for (let i = coin; i <= amount; i++) {
dp[i] += dp[i - coin];
}
}
return dp[amount];
}
console.log(coinChangeWays([1, 3, 4], 4));Attempts:
2 left
💡 Hint
Count all combinations of coins that sum to 4.
✗ Incorrect
Ways to make 4: {1+1+1+1}, {1+3}, {4} → 3 ways total.
🔧 Debug
advancedIdentify the Error in Coin Change Code
What error does this code produce when run, and why?
DSA Javascript
function coinChangeWays(coins, amount) {
const dp = Array(amount + 1).fill(0);
dp[0] = 1;
for (let i = 0; i <= coins.length; i++) {
for (let j = coins[i]; j <= amount; j++) {
dp[j] += dp[j - coins[i]];
}
}
return dp[amount];
}
console.log(coinChangeWays([1, 2, 3], 4));Attempts:
2 left
💡 Hint
Check the loop condition for accessing coins array.
✗ Incorrect
The loop runs with i <= coins.length, so when i equals coins.length, coins[i] is undefined causing dp[j - coins[i]] to fail with TypeError.
🧠 Conceptual
advancedUnderstanding DP Array in Coin Change
In the coin change total ways algorithm, what does dp[i] represent after the loops complete?
Attempts:
2 left
💡 Hint
Think about what the dp array accumulates as the algorithm progresses.
✗ Incorrect
dp[i] stores the count of different ways to make amount i using the coins processed up to that point.
❓ Predict Output
expertOutput of Coin Change with Large Amount and Coins
What is the output of this code for amount 10 with coins [2, 5, 3, 6]?
DSA Javascript
function coinChangeWays(coins, amount) {
const dp = Array(amount + 1).fill(0);
dp[0] = 1;
for (const coin of coins) {
for (let i = coin; i <= amount; i++) {
dp[i] += dp[i - coin];
}
}
return dp[amount];
}
console.log(coinChangeWays([2, 5, 3, 6], 10));Attempts:
2 left
💡 Hint
Count all combinations of coins that sum to 10.
✗ Incorrect
The ways to make 10 with coins [2,3,5,6] are 6 distinct combinations.
