Skip to content

Commit ebb797b

Browse files
authored
Create subarray-sum-equals-k.py
1 parent 430b45c commit ebb797b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Python/subarray-sum-equals-k.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# Given an array of integers and an integer k,
5+
# you need to find the total number of continuous subarrays whose sum equals to k.
6+
#
7+
# Example 1:
8+
# Input:nums = [1,1,1], k = 2
9+
# Output: 2
10+
#
11+
# Note:
12+
# The length of the array is in range [1, 20,000].
13+
# The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
14+
15+
class Solution(object):
16+
def subarraySum(self, nums, k):
17+
"""
18+
:type nums: List[int]
19+
:type k: int
20+
:rtype: int
21+
"""
22+
result = 0
23+
accumulated_sum = 0
24+
lookup = collections.defaultdict(int)
25+
lookup[0] += 1
26+
for num in nums:
27+
accumulated_sum += num
28+
result += lookup[accumulated_sum - k]
29+
lookup[accumulated_sum] += 1
30+
return result

0 commit comments

Comments
 (0)