JavaScript Program for Find k pairs with smallest sums in two arrays


In this article, we will first find all the pairs that can be made with two arrays. Then, according to the value of k, we will display the pairs with the smallest sums in two arrays.

Here, we will first use the brute-force method to solve the problem, then we will use various methods to optimize the same. So, let’s get started with the problem statement and some examples.

Problem Statement

We are given with the two arrays arr1[] and arr2[] sorted in ascending order, and a nonnegative integer k, the objective is to find k pairs with the smallest sum such that one element of each pair belongs to arr1[] and the other element belongs to arr2[]. Let’s see some examples to clear our concepts.

Example

Input

arr1[] = [2, 3, 6, 7, 9]
arr2[] = [1, 4, 8, 10]
k = 1

Output

[2, 1]

Explanation − The first smallest sum pair is [2, 1] which is obtained from [2, 1], [3, 1], [6, 1], [7, 1], [9, 1], [2, 4], [3, 4], [6, 4], [7, 4], [9, 4], [2, 8], [3, 8], [6, 8], [7, 8], [9, 8], [2, 10], [3, 10], [6, 10], [7, 10], [9, 10].

Example

Input

arr1[] = {2, 4, 6, 8}
arr2[] = {1, 3, 5, 7}
k = 4

Output

[2, 1],
[2, 3],
[4, 1],
[4, 3]

Explanation − The first 4 pairs are returned from the sequence [2, 1], [2, 3], [4, 1], [4, 3], [6, 1], [6, 3], [8, 1], [6, 5], [8, 3], [8, 5], [6, 7], [8, 7]

Now let’s see various ways to solve the above problem.

Method 1: Brute Force

The brute force approach to solve this problem involves generating all possible pairs from the given two arrays and then selecting the k pairs with the smallest sums. this approach has a time complexity of O(n^2 log n), which is not efficient for large input sizes.

Algorithm

  • Initialize an empty list called 'pairs' to store all possible pairs.

  • Loop through each element 'a' in the first array 'arr1'.

  • Loop through each element 'b' in the second array 'arr2'.

  • Append a new pair '[a, b]' and its sum 'a + b' to the 'pairs' list.

  • Sort the 'pairs' list in ascending order based on the sum of each pair.

  • Extract the first 'k' pairs from the sorted 'pairs' list.

  • Return the 'k' pairs as the result.

Example

<!DOCTYPE html>
<html>
<body>
   <div>
      <h3>Given Arrays:</h3>
      <p id="arr1"></p>
      <p id="arr2"></p>
   </div>
   <div>
      <label for="k">Enter k:</label>
      <input type="number" id="k" name="k" value="2">
      <button onclick="findKPairs()">Find</button>
   </div>
   <div id="output"></div>
   <script>
      let arr1 = [1, 7, 11];
      let arr2 = [2, 4, 6];
      const kInput = document.getElementById('k');
      const output = document.getElementById('output');
      const arr1El = document.getElementById('arr1');
      const arr2El = document.getElementById('arr2');

      function displayArrays() {
         arr1El.textContent = `arr1 = [${arr1.join(', ')}]`;
         arr2El.textContent = `arr2 = [${arr2.join(', ')}]`;
      }

      function findKPairs() {
         const k = parseInt(kInput.value);
         let pairs = [];

         for (let i = 0; i < arr1.length; i++) {
            for (let j = 0; j < arr2.length; j++) {
               pairs.push([arr1[i], arr2[j], arr1[i] + arr2[j]]);
            }
         }

         pairs.sort((a, b) => a[2] - b[2]);
         const result = pairs.slice(0, k).map(pair => `[${pair[0]}, ${pair[1]}]`);

         output.innerHTML = result;
      }

      displayArrays();
   </script>
</body>
</html>

Method 2: Two Pointer Approach

The two pointer approach requires initializing two pointers, one for each array, to the array's beginning. Finally, using these pointers, we iterate through the arrays, comparing the sums of the elements at the current pointer positions and storing the pairings with the k least sums. We just shift the pointer corresponding to the smaller element ahead at each step to make this process as efficient as possible.

We can observe from this two-pointer approach that the above problem has an O(k log k) time complexity, which is substantially faster than the O(n2) time complexity required by a brute force approach.

Algorithm

  • Initialize pointers i and j to the beginning of arrays nums1 and nums2, respectively.

  • Initialize an empty list pair to store the k pairs with smallest sums.

  • While both pointers i and j are within the bounds of their respective arrays and the length of pairs is less than k −

    • Calculate the sum of the elements at the current pointer positions, and add this pair to pairs.

    • If nums1[i] is less than or equal to nums2[j], move pointer i forward by 1. Otherwise, move pointer j forward by 1.

  • Return pairs.

Example

<!DOCTYPE html>
<html>
<body>
   <div id="input"></div>
   <div id="output"></div>
   <script>
      function findKPairsWithSmallestSums(nums1, nums2, k) {
         const pairs = [];
         let i = 0,
         j = 0;
      while (i < nums1.length && j < nums2.length && pairs.length < k) {
         const sum = nums1[i] + nums2[j];
         pairs.push([nums1[i], nums2[j], sum]);
         if (nums1[i] <= nums2[j]) {
            i++;
         } else {
            j++;
         }
      }
      return pairs;
   }
   
   // Example usage
   const nums1 = [1, 2, 4, 5, 6];
   const nums2 = [1, 3, 4, 7, 8];
   const k = 3;
   
   // Display the input arrays using innerHTML
   const inputDiv = document.getElementById("input");
   inputDiv.innerHTML = `<h3>Input arrays:</h3>nums1 = [${nums1}], nums2 = [${nums2}]<br><br>`;
   const pairs = findKPairsWithSmallestSums(nums1, nums2, k);
   
   // Display the results using innerHTML
   const outputDiv = document.getElementById("output");
   outputDiv.innerHTML = "<h3>K pairs with smallest sums:</h3>";
   for (let i = 0; i < pairs.length; i++) {
      outputDiv.innerHTML += `[${pairs[i][0]}, ${pairs[i][1]}] = ${pairs[i][2]}<br>`;
   }
   </script>
</body>
</html>

Conclusion

In this tutorial, we have discussed writing a program to find k pairs with the smallest sums in two arrays. We used brute force method first then optimized it with a two pointer approach.

Updated on: 10-Apr-2023

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements