Finding a number of pairs from arrays with smallest sums in JavaScript

Problem

We are required to write a JavaScript function that takes in two sorted arrays of Integers as the first and the second argument respectively, arr1 and arr2.

The third argument to the function will be a number, num, and num will always be lesser than the length of both the arrays. The task of our function is to pick (num) pairs of Integers.

Each pair should have its first element from arr1 and second from arr2. The pairs should be picked such that the pairs have the smallest possible sum. Lastly our function should return an array of all these (num) pairs.

For example, if the input to the function is −

const arr1 = [1, 1, 2];
const arr2 = [1, 2, 3];
const num = 2;

Then the output should be −

const output = [
[1, 1], [1, 1]
]

Example

The code for this will be −

Live Demo

const arr1 = [1, 1, 2];
const arr2 = [1, 2, 3];
const num = 2;
const smallestPairs = (arr1 = [], arr2 = [], num = 1) => {
const temp = Array(arr1.length).fill(0);
const res = [];
let compute = () => {
let flag = Infinity;
for (let i = 0; i < arr1.length; i++) {
if (temp[i] < arr2.length && flag > (arr1[i] + arr2[temp[i]])) {
flag = arr1[i] + arr2[temp[i]];
}
}
if (flag === Infinity || res.length >= num) {
return;
} else {
for (let i = 0; i < arr1.length; i++) {
if (temp[i] < arr2.length && flag == (arr1[i] + arr2[temp[i]])) {
res.push(Array.of(arr1[i], arr2[temp[i]]));
temp[i]++;
}
}
compute();
}
}
compute();
return res.slice(0, num);
};
console.log(smallestPairs(arr1, arr2, num));

Output

And the output in the console will be −

[ [ 1, 1 ], [ 1, 1 ] ]

Updated on: 18-Mar-2021

128 Views