Subarray Sum Equals K Using Hash Map in DSA Python - 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 list gets bigger?
Analyze the time complexity of the following code snippet.
def subarray_sum(nums, k):
count = 0
current_sum = 0
sums = {0: 1}
for num in nums:
current_sum += num
if current_sum - k in sums:
count += sums[current_sum - k]
sums[current_sum] = sums.get(current_sum, 0) + 1
return count
This code counts how many continuous parts of the list add up exactly to k using a hash map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop through the list, checking and updating the hash map.
- How many times: Once for each number in the list (n times).
Each new number adds a fixed amount of work: updating sums and checking the map.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and updates |
| 100 | About 100 checks and updates |
| 1000 | About 1000 checks and updates |
Pattern observation: Operations grow directly with the size of the list.
Time Complexity: O(n)
This means the time needed grows in a straight line with the list size.
[X] Wrong: "Because of the nested map check, this must be O(n²)."
[OK] Correct: The map check is a quick lookup, not a loop, so it stays O(1) each time.
Understanding this helps you solve many problems where you track sums or counts efficiently.
"What if we used a list instead of a hash map for sums? How would the time complexity change?"
Practice
Subarray Sum Equals K problem?Solution
Step 1: Understand the problem goal
The problem requires finding the number of continuous subarrays whose sum equals a target value k.Step 2: Role of hash map in solution
A hash map stores cumulative sums encountered so far and their counts. This allows quick checking if a previous cumulative sum exists that can form a subarray summing to k.Final Answer:
To store cumulative sums and their frequencies for quick lookup -> Option DQuick Check:
Hash map stores sums [OK]
- Thinking hash map stores array elements as keys
- Assuming sorting is needed
- Using hash map to track max length instead of sums
Solution
Step 1: Understand initialization role
We initialize the hash map with cumulative sum 0 having count 1 to handle subarrays starting from index 0.Step 2: Check each option
hash_map = {0: 1} correctly initializes with {0: 1}. hash_map = {} is empty, missing initial sum. hash_map = {k: 0} uses undefined k. hash_map = {None: 0} uses None key which is incorrect.Final Answer:
hash_map = {0: 1} -> Option AQuick Check:
Start with sum 0 count 1 [OK]
- Not initializing with {0:1}
- Using empty dictionary without base case
- Using invalid keys like None or undefined variables
def subarray_sum(nums, k):
count = 0
cum_sum = 0
hash_map = {0: 1}
for num in nums:
cum_sum += num
if cum_sum - k in hash_map:
count += hash_map[cum_sum - k]
hash_map[cum_sum] = hash_map.get(cum_sum, 0) + 1
return count
print(subarray_sum([1, 2, 3], 3))Solution
Step 1: Trace cumulative sums and hash map updates
nums = [1,2,3], k=3 - cum_sum=1, hash_map={0:1,1:1}, cum_sum-k= -2 not in map - cum_sum=3, hash_map={0:1,1:1,3:1}, cum_sum-k=0 in map count=1 - cum_sum=6, hash_map={0:1,1:1,3:1,6:1}, cum_sum-k=3 in map count=1+1=2Step 2: Final count of subarrays
Two subarrays sum to 3: [1,2] and [3].Final Answer:
2 -> Option BQuick Check:
Subarrays [1,2], [3] = 2 [OK]
- Not updating count correctly
- Ignoring initial hash_map entry
- Miscounting subarrays overlapping
def subarray_sum(nums, k):
count = 0
cum_sum = 0
hash_map = {0: 0}
for num in nums:
cum_sum += num
if cum_sum - k in hash_map:
count += hash_map[cum_sum - k]
hash_map[cum_sum] = hash_map.get(cum_sum, 0) + 1
return count
print(subarray_sum([1, 1, 1], 2))Solution
Step 1: Check hash_map initialization
hash_map is initialized as {0: 0}, but it should be {0: 1} to count subarrays starting at index 0.Step 2: Effect of wrong initialization
With {0: 0}, the code misses counting subarrays that start from the beginning, leading to incorrect count.Final Answer:
hash_map initialized with {0: 0} instead of {0: 1} -> Option AQuick Check:
Initialize {0:1} to count empty prefix [OK]
- Setting initial count to 0 instead of 1
- Resetting cum_sum inside loop incorrectly
- Ignoring hash_map update line
nums = [3, 4, 7, 2, -3, 1, 4, 2] and k = 7, how many subarrays sum to k? Use the hash map approach.Solution
Step 1: Calculate cumulative sums and track counts
nums = [3,4,7,2,-3,1,4,2], k=7
- cum=3, -4 not, map={0:1,3:1}, count=0
- cum=7, 0 yes (+1), count=1, map={...,7:1}
- cum=14, 7 yes (+1), count=2, map={...,14:1}
- cum=16, 9 no, count=2, map={...,16:1}
- cum=13, 6 no, count=2, map={...,13:1}
- cum=14, 7 yes (+1), count=3, map={...,14:2}
- cum=18, 11 no, count=3, map={...,18:1}
- cum=20, 13 yes (+1), count=4, map={...,20:1}Step 2: Count total subarrays
Four subarrays sum to 7: [3,4], [7], [7,2,-3,1], [1,4,2].Final Answer:
4 -> Option CQuick Check:
Count subarrays using cum_sum and map = 4 [OK]
- Not counting repeated cumulative sums correctly
- Forgetting negative numbers affect sums
- Miscounting overlapping subarrays
Ready to prove it?
Pass the test and this pattern moves unknown
