Challenge - 5 Problems
Subarray Sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Subarray Sum Count
What is the output of the following JavaScript code that counts subarrays summing to k using a hash map?
DSA Javascript
function subarraySum(nums, k) {
let count = 0, sum = 0;
const map = new Map();
map.set(0, 1);
for (const num of nums) {
sum += num;
if (map.has(sum - k)) {
count += map.get(sum - k);
}
map.set(sum, (map.get(sum) || 0) + 1);
}
return count;
}
console.log(subarraySum([1, 2, 3], 3));Attempts:
2 left
💡 Hint
Think about all subarrays that add up to 3: [1,2] and [3].
✗ Incorrect
The subarrays that sum to 3 are [1,2] and [3], so the count is 2.
❓ Predict Output
intermediateResult of Subarray Sum with Negative Numbers
What does this code print when counting subarrays summing to k with negative numbers?
DSA Javascript
function subarraySum(nums, k) {
let count = 0, sum = 0;
const map = new Map();
map.set(0, 1);
for (const num of nums) {
sum += num;
if (map.has(sum - k)) {
count += map.get(sum - k);
}
map.set(sum, (map.get(sum) || 0) + 1);
}
return count;
}
console.log(subarraySum([1, -1, 0], 0));Attempts:
2 left
💡 Hint
Consider subarrays that sum to zero including single elements and combinations.
✗ Incorrect
Subarrays summing to 0 are [1, -1], [0], and [1, -1, 0], total 3.
🔧 Debug
advancedIdentify the Error in Subarray Sum Code
What error does this code produce when counting subarrays summing to k?
DSA Javascript
function subarraySum(nums, k) {
let count = 0, sum = 0;
const map = new Map();
for (const num of nums) {
sum += num;
if (map.has(sum - k)) {
count += map.get(sum - k);
}
map.set(sum, (map.get(sum) || 0) + 1);
}
return count;
}
console.log(subarraySum([1, 2, 3], 3));Attempts:
2 left
💡 Hint
Check if the initial map setup is missing.
✗ Incorrect
The map does not have the initial prefix sum 0 set, so subarrays like [1,2] starting from index 0 are not counted, but [3] is counted, resulting in 1 instead of 2.
🧠 Conceptual
advancedWhy Use a Hash Map in Subarray Sum Problem?
Why is a hash map used in the subarray sum equals k problem instead of nested loops?
Attempts:
2 left
💡 Hint
Think about how to count subarrays efficiently.
✗ Incorrect
The hash map stores prefix sums and their counts, allowing counting subarrays in one pass with O(n) time.
❓ Predict Output
expertOutput of Complex Subarray Sum Case
What is the output of this code counting subarrays summing to k with repeated elements?
DSA Javascript
function subarraySum(nums, k) {
let count = 0, sum = 0;
const map = new Map();
map.set(0, 1);
for (const num of nums) {
sum += num;
if (map.has(sum - k)) {
count += map.get(sum - k);
}
map.set(sum, (map.get(sum) || 0) + 1);
}
return count;
}
console.log(subarraySum([3, 4, 7, 2, -3, 1, 4, 2], 7));Attempts:
2 left
💡 Hint
Count all subarrays that sum to 7 carefully.
✗ Incorrect
The subarrays summing to 7 are [3,4], [7], [7,2,-3,1], and [1,4,2], total 4.
