Subarray Sum Equals K LeetCode Solution

Here, We see Subarray Sum Equals K LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Subarray Sum Equals K LeetCode Solution

Subarray Sum Equals K LeetCode Solution

Problem Statement

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

Subarray Sum Equals K Leetcode Solution C++

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int,int> mp;
        int sum=0,ans=0;
        mp[sum] = 1;
        for(auto it:nums){
            sum += it;
            int find = sum - k;
            if(mp.find(find) != mp.end()){
                ans += mp[find];
            }
            mp[sum]++;
        }
        return ans;
    }
};Code language: PHP (php)

Subarray Sum Equals K Leetcode Solution Java

public class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0;
        int[] sum = new int[nums.length + 1];
        sum[0] = 0;
        for (int i = 1; i <= nums.length; i++)
            sum[i] = sum[i - 1] + nums[i - 1];
        for (int start = 0; start < sum.length; start++) {
            for (int end = start + 1; end < sum.length; end++) {
                if (sum[end] - sum[start] == k)
                    count++;
            }
        }
        return count;
    }
}Code language: PHP (php)

Subarray Sum Equals K Solution JavaScript

var subarraySum = function(nums, k) {
    let sum = 0;
    let count = 0;
    let map = new Map();
    map.set(0, 1);
    for (let i = 0; i < nums.length; i++) {
        sum += nums[i];
        let rem = sum - k;
        if (map.has(rem)) {
            count += map.get(rem);
        }
        map.set(sum, (map.get(sum) || 0) + 1);
    }
    return count;
};Code language: JavaScript (javascript)

Subarray Sum Equals K Solution Python

class Solution(object):
    def subarraySum(self, nums, k):
        sum = 0
        count = 0
        map = defaultdict(int)
        map[0] = 1
        for num in nums:
            sum += num
            rem = sum - k
            if rem in map:
                count += map[rem]
            map[sum] += 1
        return count
Scroll to Top