Given two integer arrays, find all subarrays whose sum equals a specified target number. For example, if array1 = [1,2,3,4] and array2 = [7,3,4], with the sumToFind being 5, the function findSubArrays(array1, array2, num) should output [[1,4],[2,3]].
I initially approached this problem using a nested loop, resulting in a time complexity of O(N2). Is there a way to optimize this function to achieve an O(N) complexity?
function findSubArray(array1, array2, sumToFind){
var len1 = array1.length;
var len2 = array2.length;
var result=[];
for(var i=0;i<len1;i++){
for(var j=0;j<len2;j++){
if(array1[i] + array2[j] === sumToFind){
result.push([array1[i], array2[j]]);
}
}
}
return result;
}