560. Subarray Sum Equals K
Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 45% Topics: Array, Hash Table, Prefix Sum
View full problem on LeetCode Reading material
Reference solution (spoiler · python)
# Time: O(n)
# Space: O(n)
import collections
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
result = 0
accumulated_sum = 0
lookup = collections.defaultdict(int)
lookup[0] += 1
for num in nums:
accumulated_sum += num
result += lookup[accumulated_sum - k]
lookup[accumulated_sum] += 1
return result
Solution from kamyu104/LeetCode-Solutions · MIT