Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the variable that stores the count of subarrays.
DSA Javascript
let count = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Initializing count to 1 instead of 0
Using null or undefined for count
✗ Incorrect
We start counting subarrays from zero, so count should be initialized to 0.
2fill in blank
mediumComplete the code to update the cumulative sum with the current number in the array.
DSA Javascript
sum [1]= nums[i];Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition
Using multiplication or division
✗ Incorrect
We add the current number to the cumulative sum to keep track of the sum of elements so far.
3fill in blank
hardFix the error in checking if (sum - k) exists in the map.
DSA Javascript
if (map.has(sum [1] k)) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using sum + k instead of sum - k
Using multiplication or division
✗ Incorrect
We check if (sum - k) exists because it means a subarray sums to k ending at current index.
4fill in blank
hardFill both blanks to update the count and map correctly inside the loop.
DSA Javascript
count [1]= map.get(sum - k) || 0; map.set(sum, (map.get(sum) || 0) [2] 1);
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition
Using multiplication or division
✗ Incorrect
We add the number of times (sum - k) occurred to count, and increment the count of current sum in map by 1.
5fill in blank
hardFill all three blanks to complete the function that returns the count of subarrays summing to k.
DSA Javascript
function subarraySum(nums, k) {
let count = [1];
let sum = 0;
let map = new Map();
map.set(0, [2]);
for (let i = 0; i < nums.length; i++) {
sum [3]= nums[i];
if (map.has(sum - k)) {
count += map.get(sum - k);
}
map.set(sum, (map.get(sum) || 0) + 1);
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing count to 1
Setting map.set(0, 0) instead of 1
Using '-' instead of '+=' for sum update
✗ Incorrect
Initialize count to 0, set the frequency of prefix sum 0 to 1 (to handle subarrays from index 0), and update the cumulative sum using '+='.
