Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate the total sum of the array.
DSA Javascript
const totalSum = nums[1]((a, b) => a + b, 0);
Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of reduce, which returns an array instead of a single sum.
Using forEach which does not return a value.
✗ Incorrect
The reduce method sums all elements in the array to get the total sum.
2fill in blank
mediumComplete the code to check if the total sum is odd and return false if so.
DSA Javascript
if (totalSum [1] 2 !== 0) return false;
Attempts:
3 left
💡 Hint
Common Mistakes
Using + or - instead of modulo operator.
Using * which multiplies instead of checking remainder.
✗ Incorrect
Using the modulo operator (%) checks if the sum is odd by checking remainder when divided by 2.
3fill in blank
hardFix the error in the loop to iterate through nums correctly.
DSA Javascript
for (let i = 0; i [1] nums.length; i++) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes index out of range error.
Using > or >= causes the loop to never run or run incorrectly.
✗ Incorrect
The loop should run while i is less than nums.length to avoid going out of bounds.
4fill in blank
hardFill both blanks to update the dp array for subset sums.
DSA Javascript
for (let j = target; j >= [1]; j--) { dp[j] = dp[j] || dp[j [2] nums[i]]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of subtraction causes incorrect indexing.
Looping forwards causes incorrect dp updates.
✗ Incorrect
We iterate backwards from target down to nums[i], and update dp[j] by checking dp[j - nums[i]].
5fill in blank
hardFill all three blanks to create the final function that returns if partition is possible.
DSA Javascript
function canPartition(nums) {
const totalSum = nums[1]((a, b) => a + b, 0);
if (totalSum [2] 2 !== 0) return false;
const target = totalSum / 2;
const dp = Array(target + 1).fill(false);
dp[0] = true;
for (let i = 0; i < nums.length; i++) {
for (let j = target; j >= nums[i]; j--) {
dp[j] = dp[j] || dp[j [3] nums[i]];
}
}
return dp[target];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of reduce for sum.
Using addition instead of modulo for odd check.
Using addition instead of subtraction in dp update.
✗ Incorrect
The function sums the array with reduce, checks odd sum with %, and updates dp using subtraction.
