I am working on the 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 the following 2 solutions. But the problem with both of them is that I iterate over both arrays. First I go through the first array and inside this loop I through the second array. And add items at these two indexes to see if adding them matches the answer. It works fine and outputs the correct answer. The problem is submission. If we have 10,000 integers in both arrays, then these loops will require a lot of resources, such as time, processor and memory, that will be executed and get an answer.
How can I solve a more specific problem in a 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;
}