Challenge - 5 Problems
Subarray Sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of subarray sum count with negative numbers
What is the output of the following code that counts subarrays summing to k using a hash map?
DSA Python
def subarray_sum(nums, k): count = 0 current_sum = 0 sum_map = {0: 1} for num in nums: current_sum += num if current_sum - k in sum_map: count += sum_map[current_sum - k] sum_map[current_sum] = sum_map.get(current_sum, 0) + 1 return count print(subarray_sum([1, -1, 0], 0))
Attempts:
2 left
💡 Hint
Think about all subarrays that sum to zero, including those with negative numbers.
✗ Incorrect
The subarrays that sum to 0 are: [1, -1], [-1, 0], and [0]. So total count is 3.
❓ Predict Output
intermediate2:00remaining
Count subarrays summing to k with repeated elements
What does this code print when counting subarrays summing to 3?
DSA Python
def subarray_sum(nums, k): count = 0 current_sum = 0 sum_map = {0: 1} for num in nums: current_sum += num if current_sum - k in sum_map: count += sum_map[current_sum - k] sum_map[current_sum] = sum_map.get(current_sum, 0) + 1 return count print(subarray_sum([1, 2, 1, 2, 1], 3))
Attempts:
2 left
💡 Hint
Count all subarrays that sum exactly to 3, including overlapping ones.
✗ Incorrect
The subarrays summing to 3 are: [1,2], [2,1], [1,2], [2,1]. Total 4.
🔧 Debug
advanced2:00remaining
Identify the error in subarray sum code
What error does this code raise when run?
DSA Python
def subarray_sum(nums, k): count = 0 current_sum = 0 sum_map = {} for num in nums: current_sum += num if current_sum - k in sum_map: count += sum_map[current_sum - k] sum_map[current_sum] = sum_map.get(current_sum, 0) + 1 return count print(subarray_sum([1, 2, 3], 3))
Attempts:
2 left
💡 Hint
Check if the initial sum_map contains the prefix sum 0.
✗ Incorrect
sum_map is empty initially, so checking current_sum - k for 0 fails with KeyError.
❓ Predict Output
advanced2:00remaining
Output of subarray sum count with zeros and k=0
What is the output of this code counting subarrays summing to 0?
DSA Python
def subarray_sum(nums, k): count = 0 current_sum = 0 sum_map = {0: 1} for num in nums: current_sum += num if current_sum - k in sum_map: count += sum_map[current_sum - k] sum_map[current_sum] = sum_map.get(current_sum, 0) + 1 return count print(subarray_sum([0, 0, 0], 0))
Attempts:
2 left
💡 Hint
Count all subarrays of zeros that sum to zero.
✗ Incorrect
All subarrays of zeros sum to zero: [0], [0], [0], [0,0], [0,0], [0,0,0] total 6.
🧠 Conceptual
expert2:00remaining
Why use a hash map for subarray sum equals k?
Which reason best explains why a hash map is used in the subarray sum equals k problem?
Attempts:
2 left
💡 Hint
Think about how prefix sums help find subarrays quickly.
✗ Incorrect
The hash map stores counts of prefix sums to quickly find how many previous sums match current_sum - k.