Welcome to Subscribe On Youtube

560. Subarray Sum Equals K

Description

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

A subarray is a contiguous non-empty sequence of elements within an array.

 

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

Solutions

Use a map to store each sum and the count of subarrays of the sum. Put sum 0 with count 1 to the map initially.

Loop over nums and calculate the total sum sum. For each num in nums, add num to sum, and obtain the count of subarrays with sum sum - k. Add the sum to the result. Then update the map with the count of subarrays with sum sum. Finally, return the result.

  • class Solution {
        public int subarraySum(int[] nums, int k) {
            Map<Integer, Integer> counter = new HashMap<>();
            counter.put(0, 1);
            int ans = 0, s = 0;
            for (int num : nums) {
                s += num;
                ans += counter.getOrDefault(s - k, 0);
                counter.put(s, counter.getOrDefault(s, 0) + 1);
            }
            return ans;
        }
    }
    
  • class Solution {
    public:
        int subarraySum(vector<int>& nums, int k) {
            unordered_map<int, int> counter;
            counter[0] = 1;
            int ans = 0, s = 0;
            for (int& num : nums) {
                s += num;
                ans += counter[s - k];
                ++counter[s];
            }
            return ans;
        }
    };
    
  • class Solution:
        def subarraySum(self, nums: List[int], k: int) -> int:
            dp = Counter({0: 1})
            ans = s = 0
            for num in nums:
                s += num
                ans += dp[s - k] # not matter if the same num like [1,1]
                dp[s] += 1
            return ans
    
    #############
    
    class Solution: # over time limit, not fast enough
        def subarraySum(self, nums: List[int], k: int) -> int:
            count = 0
    
            # sum value from 1 to i-th element
            sum_arr = [0] * (len(nums) + 1)
    
            # cached sum
            for i in range(1, len(nums) + 1):
                sum_arr[i] = sum_arr[i - 1] + nums[i - 1]
    
            for start in range(len(nums)):
                for end in range(start + 1, len(nums) + 1):
                    if sum_arr[end] - sum_arr[start] == k:
                        count += 1
    
            return count
    
    
  • func subarraySum(nums []int, k int) int {
    	counter := map[int]int{0: 1}
    	ans, s := 0, 0
    	for _, num := range nums {
    		s += num
    		ans += counter[s-k]
    		counter[s]++
    	}
    	return ans
    }
    
  • function subarraySum(nums: number[], k: number): number {
        let ans = 0,
            s = 0;
        const counter = new Map();
        counter.set(0, 1);
        for (const num of nums) {
            s += num;
            ans += counter.get(s - k) || 0;
            counter.set(s, (counter.get(s) || 0) + 1);
        }
        return ans;
    }
    
    
  • use std::collections::HashMap;
    
    impl Solution {
        pub fn subarray_sum(nums: Vec<i32>, k: i32) -> i32 {
            let mut res = 0;
            let mut sum = 0;
            let mut map = HashMap::new();
            map.insert(0, 1);
            nums.iter().for_each(|num| {
                sum += num;
                res += map.get(&(sum - k)).unwrap_or(&0);
                map.insert(sum, map.get(&sum).unwrap_or(&0) + 1);
            });
            res
        }
    }
    
    

All Problems

All Solutions