##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/560.html

# 560. Subarray Sum Equals K

Medium

## Description

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

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

Output: 2

Note:

1. The length of the array is in range [1, 20,000].
2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

## Solution

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.

• 
public class Subarray_Sum_Equals_K {

public static void main(String[] args) {
Subarray_Sum_Equals_K out = new Subarray_Sum_Equals_K();
Solution s = out.new Solution();

System.out.println(s.subarraySum(new int[]{1, 1, 1}, 2));
}

// time: O(N)
// space: O(N)

// https://leetcode.com/problems/subarray-sum-equals-k/solution/
class Solution_hashmap {
public int subarraySum(int[] nums, int k) {

// sum => count of to-this-sum
HashMap <Integer, Integer> hm = new HashMap<>();
hm.put(0, 1);

int count = 0;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (hm.containsKey(sum - k)) { // same idea as, if (sum[end] - sum[start] == k) {
count += hm.get(sum - k);
}

hm.put(sum, hm.getOrDefault(sum, 0) + 1);
}

return count;
}
}

// time: O(N^2)
// space: O(1)
class Solution_withNoExtraSpace {
public int subarraySum(int[] nums, int k) {
int count = 0;
for (int start = 0; start < nums.length; start++) {
int sum = 0; // @note: sum for each start point
for (int end = start; end < nums.length; end++) {
sum += nums[end];
if (sum == k)
count++;
}
}
return count;
}
}

// time: O(N^2)
// space: O(N)
class Solution2 {
public int subarraySum(int[] nums, int k) {
int count = 0;

// sum value from 1 to i-th element
int[] sum = new int[nums.length + 1];
sum[0] = 0;

// cached sum
for (int i = 1; i <= nums.length; i++) {
sum[i] = sum[i - 1] + nums[i - 1];
}

for (int start = 0; start < nums.length; start++) {
for (int end = start + 1; end <= nums.length; end++) {
if (sum[end] - sum[start] == k) {
count++;
}
}
}
return count;
}
}

// brute force
class Solution {
int count = 0;

public int subarraySum(int[] nums, int k) {

for (int start = 0; start < nums.length; start++) {
for (int end = start + 1; end <= nums.length; end++) {
int sum = 0;
for (int i = start; i < end; i++) {
sum += nums[i];
}
if (sum == k)
count++;
}
}

return count;
}
}
}

############

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;
}
}

• // OJ: https://leetcode.com/problems/subarray-sum-equals-k/
// Time: O(N)
// Space: O(N)
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int ans = 0, sum = 0;
unordered_map<int, int> m{ {0, 1} };
for (int n : nums) {
sum += n;
auto it = m.find(sum - k);
if (it != m.end()) ans += it->second;
m[sum]++;
}
return ans;
}
};

• class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
counter = Counter({0: 1})
ans = s = 0
for num in nums:
s += num
ans += counter[s - k]
counter[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
}
}