Subarray Sum Equals K Using Hash Map in DSA Typescript - Time & Space Complexity
We want to understand how fast the algorithm finds subarrays that add up to a target sum.
How does the time needed grow as the input array gets bigger?
Analyze the time complexity of the following code snippet.
function subarraySum(nums: number[], k: number): number {
const map = new Map();
map.set(0, 1);
let count = 0, sum = 0;
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;
}
This code counts how many continuous parts of the array add up exactly to k using a hash map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop through the array, updating sums and checking the map.
- How many times: Exactly once for each element in the array (n times).
Each new number adds a fixed amount of work: updating sum, checking map, and updating map.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows directly with the size of the input array.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of elements.
[X] Wrong: "Because there is a nested check inside the loop, the time is O(n²)."
[OK] Correct: The map lookups and updates are fast (amortized constant time), so they don't multiply the loop work.
Understanding this pattern helps you solve many problems where you track sums or counts efficiently.
"What if we used a list instead of a hash map to store sums? How would the time complexity change?"
Practice
Subarray Sum Equals K problem?Solution
Step 1: Understand the problem goal
The problem requires finding subarrays whose sums equal a target valuek.Step 2: Role of hash map in solution
A hash map stores cumulative sums seen so far and their counts, enabling quick checks if a subarray sum equalsk.Final Answer:
To store cumulative sums and their frequencies for quick lookup -> Option AQuick Check:
Hash map stores sums = quick lookup [OK]
- Thinking hash map stores array elements as keys
- Assuming sorting is needed
- Using hash map to reverse array
Subarray Sum Equals K problem?Solution
Step 1: Identify correct Map initialization
We need a map from number to number to store cumulative sums and their counts.Step 2: Check initialization correctness
const map = new Map(); map.set(0, 1); correctly creates a Map and sets sum 0 count to 1, which is standard for this problem.Final Answer:
const map = new Map(); map.set(0, 1); -> Option AQuick Check:
Map with 0->1 set = correct init [OK]
- Using string keys instead of number keys
- Initializing map with arrays as values
- Using object syntax instead of Map methods
function subarraySum(nums: number[], k: number): number {
const map = new Map();
map.set(0, 1);
let sum = 0, count = 0;
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));Solution
Step 1: Trace cumulative sums and map updates
nums = [1,2,3], k=3 - sum=1, map has (1-3)=-2? No, map updated with sum=1 count=1 - sum=3, map has (3-3)=0? Yes, count += map.get(0)=1, map updated sum=3 count=1 - sum=6, map has (6-3)=3? Yes, count += map.get(3)=1, map updated sum=6 count=1 Total count=2Step 2: Confirm final count returned
Function returns 2, meaning two subarrays sum to 3: [1,2] and [3].Final Answer:
2 -> Option DQuick Check:
Subarrays [1,2] and [3] sum to 3 = 2 [OK]
- Counting only single elements equal to k
- Not updating map counts correctly
- Ignoring multiple subarrays with same sum
Subarray Sum Equals K and select the fix:
function subarraySum(nums: number[], k: number): number {
const map = new Map();
let sum = 0, count = 0;
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;
}Solution
Step 1: Identify missing initialization
The map must start with sum 0 count 1 to count subarrays starting at index 0.Step 2: Fix by adding map.set(0, 1)
Addingmap.set(0, 1)before the loop ensures correct counting of subarrays that start from the beginning.Final Answer:
Initialize map with map.set(0, 1) before loop -> Option BQuick Check:
map.set(0,1) needed for correct count [OK]
- Forgetting to initialize map with 0 sum
- Removing necessary condition checks
- Changing variable initial values incorrectly
nums = [3, 4, 7, 2, -3, 1, 4, 2] and k = 7, how many subarrays sum to k using the hash map approach?Solution
Step 1: Calculate cumulative sums and track counts
nums = [3,4,7,2,-3,1,4,2], k=7 - sum=3, map={0:1}, no (3-7)=-4 - sum=7, map has (7-7)=0, count=1 - sum=14, map has (14-7)=7, count=1+1=2 - sum=16, map has (16-7)=9 no - sum=13, map has (13-7)=6 no - sum=14, map has (14-7)=7, count=2+1=3 - sum=18, map has (18-7)=11 no - sum=20, map has (20-7)=13, count=3+1=4 Total count=4 Subarrays summing to 7 are: [3,4], [7], [7,2,-3,1], [1,4,2]Step 2: Confirm final count
After full iteration, total subarrays summing to 7 are 4.Final Answer:
4 -> Option CQuick Check:
Count subarrays with sum k = 4 [OK]
- Missing negative numbers affecting sums
- Not counting overlapping subarrays
- Ignoring multiple occurrences of same sum
Ready to prove it?
Pass the test and this pattern moves unknown
