Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Find K Pairs with Smallest Sums in Two Arrays



To find k pairs with smallest sums in two arrays in Javascript, we will be using sorted arrays in ascending order. We are going to discuss two different approaches with stepwise explanation and examples.

In this article we are having two arrays and a value of k, our task is to find k pairs with smallest sums in two arrays. Users must be familiar with JavaScript arrays, loops and conditional statement.

Example

Input:
arr1 = [1, 7, 11], arr2 = [2, 4, 6]
k = 3

Output:
[[1,2], [1, 4], [1, 6]]

Input:
arr1 = [1, 4, 8, 12, 15], arr2 = [2, 4, 6, 7, 9]
k = 4

Output:
[[1,2], [1, 4], [4, 2], [1, 6]]

Approaches to Find k Pairs with Smallest Sums

Here is a list of approaches to find k pairs with smallest sums in two arrays in Javascript which we will be discussing in this article with stepwise explanation and complete example codes.

Using Brute Force

To find k pairs with smallest sums in two arrays in Javascript, we have used brute force approach.

  • First we have declared two arrays as arr1 and arr2 and defined a function minSumPair() that accepts arr1, arr2 and k as its arguments.
  • Initially we have defined an empty array pairs which will keep all pairs of elements from both the arrays. We have used if/else statement to check the legal value of k.
  • Then we have used two for loops, which makes pairs of elements of both the arrays and push the pairs into array pairs using push() method.
  • Then we have used sort() function to sort the elements in array pairs based on their summation value.
  • Then we have used slice() method to get the number of pair of elements specified by variable k and displayed the output in web console using console.log().

Example

Here is a complete example code implementing above mentioned steps to find k pairs with smallest sums in two arrays in Javascript using brute force approach.

const arr1 = [1, 7, 11];
const arr2 = [2, 4, 6];
function minSumPair(arr1, arr2, k) {
    const pairs = [];
    if (k>(arr1.length * arr2.length)){
        return "Enter a valid k less than " 
                +arr1.length * arr2.length;
    }
    for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
            pairs.push([arr1[i], arr2[j]]);
        }
    }
    pairs.sort((a, b) => (a[0] + a[1]) - (b[0] + b[1]));
    return pairs.slice(0, k);
}
console.log("Pairs with smallest sum: ");
console.log(minSumPair(arr1, arr2, 3)); 

Using Greedy Approach

In this approach, to find k pairs with smallest sums in two arrays in Javascript, we have used greedy approach as we are selecting optimal solution at each step.

  • First we have declared two arrays as arr1 and arr2 and defined a function minSumPair() that accepts arr1, arr2 and k as its arguments.
  • Initially we have defined an empty array result which will keep all pairs of elements from both the arrays. We have used if/else statement to check the legal value of k.
  • Then we have created an array pointers using Array() constructor having array length same as arr1 with each element of the array as 0 using fill() method. This array keeps track of elements in arr2 for each element of arr1.
  • We have used for loop that calculates the sum of pairs of each element of arr1 with one element of arr2 at a time For e.g: (arr1[0]+arr2[0], arr1[1]+arr2[0] and arr1[2]+arr2[0]). Then if/else statement checks for minimum sum value of pairs and updates the minSum and minIndex variable.
  • The if/else statement checks if the value of minIndex is still -1. The -1 represents no pairs with minimum sum was found and terminates the while loop using break.
  • For value other than -1 of minIndex, the pair is pushed into result array and value of k is decreased by 1. The value of element in pointers array is increased by 1 at index specified by minIndex.
  • The above process is repeated till k>0 using while loop to get k pairs of smallest sums in both arrays and the result is displayed in web console using console.log().

Example

Here is a complete example code implementing above mentioned steps to find k pairs with smallest sums in two arrays in Javascript using Greedy approach.

const arr1 = [1, 7, 11];
const arr2 = [2, 4, 6];
function minSumPair(arr1, arr2, k) {
    const result = [];
    if (k>(arr1.length * arr2.length)){
        return "Enter a valid k less than " 
                +arr1.length * arr2.length;
    }
    if (arr1.length === 0 || arr2.length === 0 || k === 0) 
        return result;
    const pointers = Array(arr1.length).fill(0); 
    while (k > 0) {
        let minSum = Infinity;
        let minIndex = -1;
        for (let i = 0; i < arr1.length; i++) {
            if (pointers[i] < arr2.length) {
                const sum = arr1[i] + arr2[pointers[i]];
                if (sum < minSum) {
                    minSum = sum;
                    minIndex = i;
                }
            }
        }
        if (minIndex === -1) break;
        result.push([arr1[minIndex], 
                    arr2[pointers[minIndex]]]);
        pointers[minIndex]++;
        k--;
    }
    return result;
}
console.log("Pairs with smallest sum: ");
console.log(minSumPair(arr1, arr2, 3));

Complexity Comparison

Here is a comparison of time and space complexity of all the above approaches.

Approach Time Complexity Space Complexity
Brute Force O((n*m)*log(n*m)) O(n*m)
Greedy Approach O(k*n) O(n+k)

Conclusion

In this article to find k pairs with smallest sums in two arrays in Javascript, we have used two different approaches which are: by using brute force approach and by using greedy approach. Out of the two approaches, greedy approach is efficient than brute force.

Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.
Updated on: 2024-12-04T16:40:53+05:30

298 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements