File tree Expand file tree Collapse file tree 1 file changed +13
-15
lines changed
0560-subarray-sum-equals-k Expand file tree Collapse file tree 1 file changed +13
-15
lines changed Original file line number Diff line number Diff line change 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
66class 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
You can’t perform that action at this time.
0 commit comments