Skip to content

Commit e57781c

Browse files
committed
Sync LeetCode submission Runtime - 23 ms (96.43%), Memory - 20.4 MB (18.73%)
1 parent 7eb3826 commit e57781c

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed
Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
1-
# Approach 4 - Using Hashmap
1+
# Approach 4: Using Hashmap
22

3-
# Time: O(N)
4-
# Space: O(N)
3+
# Time: O(n)
4+
# Space: O(n)
55

66
class Solution:
77
def subarraySum(self, nums: List[int], k: int) -> int:
88
count = 0
9-
total = 0
10-
11-
hashmap = {} # {sum_i : no. of occurrences of sum_i}
12-
hashmap[0] = 1
13-
14-
for i in range(len(nums)):
15-
total += nums[i]
16-
17-
if (total - k) in hashmap.keys():
18-
count += hashmap.get(total - k)
19-
hashmap[total] = hashmap.get(total, 0) + 1
20-
9+
prefix_sum = 0
10+
sum_freq = {}
11+
sum_freq[0] = 1
12+
13+
for num in nums:
14+
prefix_sum += num
15+
if prefix_sum - k in sum_freq:
16+
count += sum_freq[prefix_sum - k]
17+
sum_freq[prefix_sum] = sum_freq.get(prefix_sum, 0) + 1
18+
2119
return count
2220

0 commit comments

Comments
 (0)