So I'm working on this problem:
Given an array with positive numbers and a target number, find all of its contiguous subarrays whose product is less than the target number.
Input: find_subarrays([2,5,3,10], 30)
Output: [2][5][2,5][3][5,3][10]
I have two arrays:
a temporary one, tmp, that is reset whenever the product of the contiguous numbers is greater than the target
a result, that holds all the contiguous arrays and is returned at the end
I originally tried using tmp.push(arr[j]) to add numbers into the tmp array and then push the tmp array into the result array.
But the result is [2,5][2,5][5,3][5,3][3][10]. I don't understand what is going on.
When I use tmp = tmp.concat(arr[j]), I get the correct output.
Why doesn't tmp.push(arr[j]) work in this situation?
My code:
const find_subarrays = function(arr, target) {
let result = [];
for (let i=0; i<arr.length; i++) {
let product = arr[i];
let tmp = [];
let j = i;
while (product < target && j < arr.length) {
tmp = tmp.concat(arr[j]);
// tmp.push(arr[j]); why doesn't this work instead of concat?
result.push(tmp)
j++;
product *= arr[j]
}
}
return result;
};