Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate the total sum of elements in the array.
DSA C++
int totalSum = 0; for (int num : nums) { totalSum [1] num; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' instead of '+=' causes subtraction instead of addition.
Using '*=' or '/=' changes the total incorrectly.
✗ Incorrect
We add each number to totalSum using the '+=' operator to get the total sum.
2fill in blank
mediumComplete the code to check if the total sum is odd, which means partition is impossible.
DSA C++
if (totalSum [1] 2 != 0) { return false; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '/' instead of '%' gives the quotient, not remainder.
Using '==' or '!=' without modulus does not check oddness.
✗ Incorrect
We use the modulus operator '%' to check if totalSum divided by 2 has a remainder, indicating oddness.
3fill in blank
hardFix the error in the dynamic programming initialization to create a boolean vector of size target+1.
DSA C++
vector<bool> dp([1], false); dp[0] = true;
Attempts:
3 left
💡 Hint
Common Mistakes
Using target or target-1 misses the last index.
Using nums.size() is unrelated to sum target size.
✗ Incorrect
We need a vector of size target+1 to include index 'target' for subset sum checks.
4fill in blank
hardFill both blanks to update the dp vector for subset sums using the current number.
DSA C++
for (int i = [1]; i >= 0; i--) { if (dp[i] && i + num [2] target) { dp[i + num] = true; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using target + num causes out-of-bound errors.
Using '>=' reverses the condition incorrectly.
✗ Incorrect
We iterate down from target - num to 0 and check if i + num is less than or equal to target to update dp.
5fill in blank
hardFill all three blanks to complete the function that returns true if the array can be partitioned into two equal subsets.
DSA C++
bool canPartition(vector<int>& nums) {
int totalSum = 0;
for (int num : nums) {
totalSum [1] num;
}
if (totalSum [2] 2 != 0) return false;
int target = totalSum / 2;
vector<bool> dp([3], false);
dp[0] = true;
for (int num : nums) {
for (int i = target - num; i >= 0; i--) {
if (dp[i] && i + num <= target) {
dp[i + num] = true;
}
}
}
return dp[target];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' instead of '+=' for sum.
Using '/' instead of '%' for odd check.
Creating dp vector with wrong size.
✗ Incorrect
We add numbers to totalSum with '+='; check oddness with '%'; and create dp vector of size target+1.
