This is a variant of this leetcode question, but instead of returning the count, we want to return the actual contiguous sub arrays. For example, if num = [1,2,4,7] k=7 the returned value should be [[1,2,4],[7]] .
I used a hashmap to store the cumulative sum up to all the indices possible along with the number of times the same sum occurs for the original question, where it asks to return the count
var subarraySum = function(nums, k) {
let sum = 0;
let count = 0;
const myMap = new Map();
myMap.set(0, 1);
for (let num of nums) {
sum += num;
count += myMap.get(sum - k) || 0;
myMap.set(sum, (myMap.get(sum) || 0) + 1);
}
return count;
}
But I cannot seem to figure out how I can adapt this solution to return the actual sub-arrays.
from JavaScript: return all contiguous subarrays whose sum equals K
No comments:
Post a Comment