Subarray Sum Equals K Using Hash Map in DSA C++ - Time & Space Complexity
We want to know 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.
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> prefixCount;
prefixCount[0] = 1;
int count = 0, sum = 0;
for (int num : nums) {
sum += num;
if (prefixCount.find(sum - k) != prefixCount.end()) {
count += prefixCount[sum - k];
}
prefixCount[sum]++;
}
return count;
}
This code counts how many continuous parts of the array add up exactly to k using a map to track sums.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop through the array elements.
- How many times: Exactly once for each element in the array.
Each new element adds a fixed amount of work: updating sum, checking the map, and updating the map.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows directly in proportion to the input size.
Time Complexity: O(n)
This means the time needed grows linearly with the number of elements in the array.
[X] Wrong: "Because we use a map inside the loop, the time is O(n²)."
[OK] Correct: The map operations (find and update) are on average constant time, so they do not multiply the loop time.
Understanding how to use a map to track sums efficiently is a valuable skill that shows you can optimize beyond simple nested loops.
"What if we replaced the unordered_map with a balanced tree map? 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
The hash map stores cumulative sums and their counts to quickly check if a previous sum exists that forms a subarray summing tok.Final Answer:
To store cumulative sums and their frequencies for quick lookup -> Option DQuick Check:
Hash map stores sums = D [OK]
- Using hash map to sort elements
- Storing array elements as keys instead of sums
- Trying to track max length instead of counts
int keys and values?Solution
Step 1: Identify correct hash map declaration
In C++,std::unordered_map<Key, Value>is used for hash maps.Step 2: Check syntax correctness
std::unordered_map map; uses correct template syntax and namespace. Others have syntax errors or wrong types.Final Answer:
std::unordered_map map; -> Option AQuick Check:
Correct unordered_map syntax = A [OK]
- Missing template brackets <>
- Using std::map instead of unordered_map for hash map
- Wrong order of template parameters
std::vector<int> nums = {1, 2, 3};
int k = 3;
int count = 0;
std::unordered_map prefixSumCount;
prefixSumCount[0] = 1;
int sum = 0;
for (int num : nums) {
sum += num;
if (prefixSumCount.find(sum - k) != prefixSumCount.end()) {
count += prefixSumCount[sum - k];
}
prefixSumCount[sum]++;
}
std::cout << count << std::endl;Solution
Step 1: Calculate prefix sums and counts
Prefix sums: 1, 3, 6. Check if (sum - k) exists in map: - sum=1: 1-3=-2 not found - sum=3: 3-3=0 found, count=1 - sum=6: 6-3=3 found, count=1+1=2Step 2: Final count of subarrays with sum k
Count is 2 because subarrays [1,2] and [3] sum to 3.Final Answer:
2 -> Option AQuick Check:
Subarrays summing to 3 = 2 [OK]
- Not initializing prefixSumCount[0] = 1
- Incorrectly updating count
- Confusing sum and sum-k keys
k:
int subarraySum(std::vector<int>& nums, int k) {
std::unordered_map map;
int count = 0, sum = 0;
for (int num : nums) {
sum += num;
if (map.find(sum - k) != map.end()) {
count += map[sum - k];
}
map[sum] = 1;
}
return count;
}Solution
Step 1: Analyze map update logic
Settingmap[sum] = 1overwrites previous counts, losing frequency data.Step 2: Correct way to update map
We must incrementmap[sum]to count all occurrences of the prefix sum.Final Answer:
map[sum] should be incremented, not set to 1 -> Option CQuick Check:
Increment map[sum] to track frequencies [OK]
- Overwriting map[sum] instead of incrementing
- Resetting sum inside loop incorrectly
- Using wrong data structure for map
nums = {3, 4, 7, 2, -3, 1, 4, 2} and k = 7, how many subarrays sum to k? Use the hash map approach to find the count.Solution
Step 1: Calculate prefix sums and track counts
Prefix sums: 3,7,14,16,13,14,18,20.
Map checks (sum-k found):
- sum=7: 0 (+1) -> count=1
- sum=14: 7 (+1) -> count=2
- sum=14 (2nd): 7 (+1) -> count=3
- sum=20: 13 (+1) -> count=4
- sum=18: 11 (+1) -> count=5 (Note: 11 is sum-k for k=7 at sum=18, check if 11 exists in map)Step 2: Final count of subarrays
Total 5 subarrays: [3,4], [7], [7,2,-3,1], [1,4,2], and [4,7,2,-3,-3].Final Answer:
5 -> Option BQuick Check:
Count of subarrays with sum 7 = 5 [OK]
- Not incrementing count for multiple occurrences
- Missing negative numbers effect on sums
- Incorrect prefix sum updates
Ready to prove it?
Pass the test and this pattern moves unknown
