Subarray Sum Equals K

Problem

Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.

For example:

Input: nums = [1,1,1], k = 2
Output: 2
Input: nums = [1,2,3], k = 3
Output: 2

Solution

class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        sumMap = {}
        count = 0
        sums = 0
        
        for i in range(len(nums)):
            sums+=nums[i]
            if sums == k:
                count+=1
            if sums-k in sumMap: #checking hash map to see is sum exists
                count+=sumMap[sums-k]
            if sums in sumMap:
                sumMap[sums]+=1
            else:
                sumMap[sums] = 1
        return count
        
#Calculating the prefix sums to i and storing it in 
#a hash map

#If currSum - k exists in hash map, then this means we
#have a subarray that is equal to k, so we can increase
#the count

#Time: O(n)
#Space: O(n)

Last updated