I am working on following example
Given: 2 sorted arrays of integers(e.g. A = [1,2,3,4,5], B = [6, 7, 8, 9, 10]) and answer(e.g 13)
Find: What I have to do is to find pair of indices(1 in each array) of those two elements in both arrays so when I add them then it should be equal to the given answer.
I used following 2 solutions. But the problem with both of them is that I am looping through both arrays. First I loop through first array and inside this I loop through second array. And add elements on those two indices to see if its addition is equal to answer. It works fine and outputs correct answer. The problem is performance. If we have 10,000 integers in both arrays then these loops will take a lot of resources such as time, CPU and memory to be executed and get answer.
How can I solve above particular problem in more efficient way?
function find (A1, A2, ans) {
var a = [];
for (var i = 0, len1 = A1.length; i < len1; i++) {
for (var j = 0, len2 = A2.length; j < len2; j++) {
if (ans === A1[i] + A2[j]) {
a.push(i + ', ' + j);
}
}
}
return a;
}
second
function search (A, B, ans) {
var arr = [];
A.map(function (v, i) {
B.filter(function (val, ind) {
if (ans === v + val) arr.push(i + ', ' +ind);
});
});
return arr;
}