LeetCode 560. Subarray Sum Equals K

May. 21, 2021

Brute Force Solution to Subarray Sum Equals K problem from LeetCode:

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var subarraySum = function(nums, k) {
    let ans = 0;

    for (let i=0; i<nums.length; i++) {
        let currSum = nums[i];
        if (currSum === k) ans++;
        for (let j=i+1; j<nums.length; j++) {
            currSum += nums[j];
            if (currSum === k) ans++;

        }
    }

    return ans;
};

Optimized solution after cheating a bit:

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var subarraySum = function(nums, k) {
    let ans = 0;
    const m = new Map();
    let sum=0;
    m.set(sum, 1);

    for (let i=0; i<nums.length; i++) {
        sum += nums[i];

        if (m.has(sum-k)) {
            ans += m.get(sum-k);
        }

        if (!m.has(sum)) {
            m.set(sum, 1);
        } else {
            m.set(sum, m.get(sum) + 1);
        }

    }

    return ans;
};

Runtime: 96 ms, faster than 94.76% of JavaScript online submissions for Subarray Sum Equals K.

Memory Usage: 46.6 MB, less than 81.14% of JavaScript online submissions for Subarray Sum Equals K.