A solution to LeetCode Problem 560. Subarray Sum Equals K in JavaScript
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
Constraints:
1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107
Solution:
function subarraySum(nums, k) { let count = 0; let sum = 0; const map = new Map(); map.set(0, 1); for (let i = 0; i < nums.length; i++) { sum += nums[i]; if (map.has(sum - k)) { count += map.get(sum - k); } map.set(sum, (map.get(sum) || 0) + 1); } return count; }
In the above code, we use a map to store the frequency of each prefix sum. We also initialize the map with a key of 0 and a value of 1, as there is always at least one subarray with a sum of 0 (the empty subarray).
As we iterate through the array, we add the current element to the sum and check if there is a previous element such that the difference between the two elements is equal to k. If we find such an element, we increment the count by the frequency of that element in the map. We also update the frequency of the current sum in the map.
This solution has a time complexity of O(n) and a space complexity of O(n), making it more efficient than the brute force method.
I hope this blog post was helpful in understanding how to solve the LeetCode Problem 560: Subarray Sum Equals K in JavaScript. If you have any questions or comments, feel free to leave them below.
You have observed very interesting details! ps nice website.Leadership
I’ve recently started a site, the information you offer on this website has helped me tremendously. Thank you for all of your time & work. “Patriotism is often an arbitrary veneration of real estate above principles.” by George Jean Nathan.
naturally like your web-site but you have to check the spelling on several of your posts. Several of them are rife with spelling issues and I find it very troublesome to tell the truth nevertheless I’ll definitely come back again.