LeetCode 560. Subarray Sum Equals K

Description

https://leetcode.com/problems/subarray-sum-equals-k/

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

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 2 * 104
  • -1000 <= nums[i] <= 1000
  • -107 <= k <= 107

Explanation

We can store the sums in a hashmap and check if sum – k in the hashmap.

Python Solution

class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
                
        count = 0
        sum = 0
        
        map = {}
        map[0] = 1
                
        for i in range(0, len(nums)):
            sum += nums[i]    
            
            if (sum - k) in map:
                count += map.get(sum - k)
            map[sum] = map.get(sum, 0) + 1
            
        
        return count
  • Time complexity: O(N).
  • Space complexity: O(N).

2 Thoughts to “LeetCode 560. Subarray Sum Equals K”

Leave a Reply

Your email address will not be published. Required fields are marked *