Given two arrays arr1[] and arr2[] sorted in ascending order and an integer K. The task is to find k pairs with the smallest sums such that one element of a pair belongs to arr1[] and another element belongs to arr2[]. The sizes of arrays may be different. Assume all the elements to be distinct in each array.Â
Examples:
Input: a1[] = {1, 7, 11}
a2[] = {2, 4, 6}
k = 3
Output: [1, 2], [1, 4], [1, 6]
The first 3 pairs are returned
from the sequence [1, 2], [1, 4], [1, 6], [7, 2],
[7, 4], [11, 2], [7, 6], [11, 4], [11, 6].
Input: a1[] = { 2, 3, 4 }
a2[] = { 1, 6, 5, 8 }
k = 4
Output: [1, 2] [1, 3] [1, 4] [2, 6]
An approach with time complexity O(k*n1) has been discussed here.Â
Efficient Approach: Since the array is already sorted. The given below algorithm can be followed to solve this problem:Â Â
- The idea is to maintain two pointers, one pointer pointing to one pair in (a1, a2) and the other in (a2, a1). Each time, compare the sums of the elements pointed by the two pairs and print the minimum one. After this, increment the pointer to the element in the printed pair which was larger than the other. This helps to get the next possible k smallest pair.
- Once the pointer has been updated to the element such that it starts pointing to the first element of the array again, update the other pointer to the next value. This update is done cyclically.
- Also, when both the pairs are pointing to the same element, update pointers in both the pairs to avoid extra pair’s printing. Update one pair’s pointer according to rule1 and other’s opposite to rule1. This is done to ensure that all the permutations are considered and no repetitions of pairs are there.
Below is the working of the algorithm for example 1:Â
Â
a1[] = {1, 7, 11}, a2[] = {2, 4}, k = 3
Let the pairs of pointers be _one, _two
_one.first points to 1, _one.second points to 2 ;Â
_two.first points to 2, _two.second points to 1
1st pair:Â
Since _one and _two are pointing to same elements, print the pair once and updateÂ
Â
- print [1, 2]
then update _one.first to 1, _one.second to 4 (following rule 1) ;Â
_two.first points to 2, _two.second points to 7 (opposite to rule 1).Â
If rule 1 was followed for both, then both of them would have been pointing to 1 and 4,Â
and it is not possible to get all possible permutations.
2nd pair:Â
Since a1[_one.first] + a2[_one.second] < a1[_two.second] + a2[_two.first], print them and updateÂ
Â
- print [1, 4]
then update _one.first to 1, _one.second to 2Â
Since _one.second came to the first element of the array once again,Â
therefore _one.first points to 7
Repeat the above process for remaining K pairs
Below is the C++ implementation of the above approach:Â
C++
// C++ program to print the k smallest// pairs | Set 2#include <bits/stdc++.h>using namespace std;Â
typedef struct _pair {Â Â Â Â int first, second;} _pair;Â
// Function to print the K smallest pairsvoid printKPairs(int a1[], int a2[],                 int size1, int size2, int k){Â
    // if k is greater than total pairs    if (k > (size2 * size1)) {        cout << "k pairs don't exist\n";        return;    }Â
    // _pair _one keeps track of    // 'first' in a1 and 'second' in a2    // in _two, _two.first keeps track of    // element in the a2[] and _two.second in a1[]    _pair _one, _two;    _one.first = _one.second = _two.first = _two.second = 0;Â
    int cnt = 0;Â
    // Repeat the above process till    // all K pairs are printed    while (cnt < k) {Â
        // when both the pointers are pointing        // to the same elements (point 3)        if (_one.first == _two.second            && _two.first == _one.second) {            if (a1[_one.first] < a2[_one.second]) {                cout << "[" << a1[_one.first]                     << ", " << a2[_one.second] << "] ";Â
                // updates according to step 1                _one.second = (_one.second + 1) % size2;                if (_one.second == 0) // see point 2                    _one.first = (_one.first + 1) % size1;Â
                // updates opposite to step 1                _two.second = (_two.second + 1) % size2;                if (_two.second == 0)                    _two.first = (_two.first + 1) % size2;            }            else {                cout << "[" << a2[_one.second]                     << ", " << a1[_one.first] << "] ";Â
                // updates according to rule 1                _one.first = (_one.first + 1) % size1;                if (_one.first == 0) // see point 2                    _one.second = (_one.second + 1) % size2;Â
                // updates opposite to rule 1                _two.first = (_two.first + 1) % size2;                if (_two.first == 0) // see point 2                    _two.second = (_two.second + 1) % size1;            }        }        // else update as necessary (point 1)        else if (a1[_one.first] + a2[_one.second]                 <= a2[_two.first] + a1[_two.second]) {            if (a1[_one.first] < a2[_one.second]) {                cout << "[" << a1[_one.first] << ", "                     << a2[_one.second] << "] ";Â
                // updating according to rule 1                _one.second = ((_one.second + 1) % size2);                if (_one.second == 0) // see point 2                    _one.first = (_one.first + 1) % size1;            }            else {                cout << "[" << a2[_one.second] << ", "                     << a1[_one.first] << "] ";Â
                // updating according to rule 1                _one.first = ((_one.first + 1) % size1);                if (_one.first == 0) // see point 2                    _one.second = (_one.second + 1) % size2;            }        }        else if (a1[_one.first] + a2[_one.second]                 > a2[_two.first] + a1[_two.second]) {            if (a2[_two.first] < a1[_two.second]) {                cout << "[" << a2[_two.first] << ", " << a1[_two.second] << "] ";Â
                // updating according to rule 1                _two.first = ((_two.first + 1) % size2);                if (_two.first == 0) // see point 2                    _two.second = (_two.second + 1) % size1;            }            else {                cout << "[" << a1[_two.second]                     << ", " << a2[_two.first] << "] ";Â
                // updating according to rule 1                _two.second = ((_two.second + 1) % size1);                if (_two.second == 0) // see point 2                    _two.first = (_two.first + 1) % size1;            }        }        cnt++;    }}Â
// Driver Codeint main(){Â
    int a1[] = { 2, 3, 4 };    int a2[] = { 1, 6, 5, 8 };    int size1 = sizeof(a1) / sizeof(a1[0]);    int size2 = sizeof(a2) / sizeof(a2[0]);    int k = 4;    printKPairs(a1, a2, size1, size2, k);    return 0;} |
Java
// Java program to print // the k smallest pairs // | Set 2import java.util.*;class GFG{Â
static class _pair {Â Â int first, second;};Â
// Function to print the K // smallest pairsstatic void printKPairs(int a1[], int a2[],                         int size1, int size2,                         int k){  // if k is greater than   // total pairs  if (k > (size2 * size1))  {    System.out.print("k pairs don't exist\n");    return;  }Â
  // _pair _one keeps track of  // 'first' in a1 and 'second' in a2  // in _two, _two.first keeps track of  // element in the a2[] and _two.second  // in a1[]  _pair _one = new _pair();  _pair _two = new _pair();  _one.first = _one.second =   _two.first = _two.second = 0;Â
  int cnt = 0;Â
  // Repeat the above process   // till all K pairs are printed  while (cnt < k)   {    // when both the pointers are     // pointing to the same elements     // (point 3)    if (_one.first == _two.second &&         _two.first == _one.second)     {      if (a1[_one.first] <           a2[_one.second])       {        System.out.print("[" + a1[_one.first] +                          ", " + a2[_one.second] +                          "] ");Â
        // updates according to step 1        _one.second = (_one.second + 1) %                        size2;                 // see point 2        if (_one.second == 0)           _one.first = (_one.first + 1) %                         size1;Â
        // updates opposite to step 1        _two.second = (_two.second + 1) %                        size2;                 if (_two.second == 0)          _two.first = (_two.first + 1) %                         size2;      }      else      {        System.out.print("[" + a2[_one.second] +                          ", " + a1[_one.first] +                          "] ");Â
        // updates according to rule 1        _one.first = (_one.first + 1) %                       size1;                 // see point 2        if (_one.first == 0)           _one.second = (_one.second + 1) %                          size2;Â
        // updates opposite to rule 1        _two.first = (_two.first + 1) %                       size2;                 // see point 2        if (_two.first == 0)                      _two.second = (_two.second + 1) %                          size1;      }    }         // else update as     // necessary (point 1)    else if (a1[_one.first] +              a2[_one.second] <=              a2[_two.first] +              a1[_two.second])     {      if (a1[_one.first] <          a2[_one.second])       {        System.out.print("[" + a1[_one.first] +                          ", " + a2[_one.second] +                          "] ");Â
        // updating according to rule 1        _one.second = ((_one.second + 1) %                         size2);                 // see point 2        if (_one.second == 0)           _one.first = (_one.first + 1) %                         size1;      }      else      {        System.out.print("[" + a2[_one.second] +                         ", " + a1[_one.first] +                          "] ");Â
        // updating according to rule 1        _one.first = ((_one.first + 1) %                        size1);                 // see point 2        if (_one.first == 0)           _one.second = (_one.second + 1) %                          size2;      }    }    else if (a1[_one.first] +              a2[_one.second] >              a2[_two.first] +              a1[_two.second])     {      if (a2[_two.first] <           a1[_two.second])       {        System.out.print("[" + a2[_two.first] +                          ", " + a1[_two.second] +                          "] ");Â
        // updating according to rule 1        _two.first = ((_two.first + 1) %                        size2);                 // see point 2        if (_two.first == 0)           _two.second = (_two.second + 1) %                          size1;      }      else {        System.out.print("[" + a1[_two.second] +                          ", " + a2[_two.first] +                          "] ");Â
        // updating according to rule 1        _two.second = ((_two.second + 1) %                         size1);                 // see point 2        if (_two.second == 0)           _two.first = (_two.first + 1) %                         size1;      }    }    cnt++;  }}Â
// Driver Codepublic static void main(String[] args){  int a1[] = {2, 3, 4};  int a2[] = {1, 6, 5, 8};  int size1 = a1.length;  int size2 = a2.length;  int k = 4;  printKPairs(a1, a2,              size1, size2, k);}}Â
// This code is contributed by gauravrajput1 |
Python3
# Python3 program to print the k smallest# pairs | Set 2Â
# Function to print the K smallest pairsdef printKPairs(a1, a,size1, size2, k):Â
    # if k is greater than total pairs    if (k > (size2 * size1)):        print("k pairs don't exist\n")        returnÂ
    # _pair _one keeps track of    # 'first' in a1 and 'second' in a2    # in _two, _two[0] keeps track of    # element in the a2and _two[1] in a1[]    _one, _two = [0, 0], [0, 0]Â
    cnt = 0Â
    # Repeat the above process till    # all K pairs are printed    while (cnt < k):Â
        # when both the pointers are pointing        # to the same elements (po3)        if (_one[0] == _two[1]            and _two[0] == _one[1]):            if (a1[_one[0]] < a2[_one[1]]):                print("[", a1[_one[0]], ", ",                         a2[_one[1]],"] ", end=" ")Â
                # updates according to step 1                _one[1] = (_one[1] + 1) % size2                if (_one[1] == 0): #see po2                    _one[0] = (_one[0] + 1) % size1Â
                # updates opposite to step 1                _two[1] = (_two[1] + 1) % size2                if (_two[1] == 0):                    _two[0] = (_two[0] + 1) % size2Â
            else:                print("[",a2[_one[1]]                    ,", ",a1[_one[0]],"] ",end=" ")Â
                # updates according to rule 1                _one[0] = (_one[0] + 1) % size1                if (_one[0] == 0): #see po2                    _one[1] = (_one[1] + 1) % size2Â
                # updates opposite to rule 1                _two[0] = (_two[0] + 1) % size2                if (_two[0] == 0): #see po2                    _two[1] = (_two[1] + 1) % size1Â
        # else update as necessary (po1)        elif (a1[_one[0]] + a2[_one[1]]                <= a2[_two[0]] + a1[_two[1]]):            if (a1[_one[0]] < a2[_one[1]]):                print("[",a1[_one[0]],", ",                    a2[_one[1]],"] ",end=" ")Â
                # updating according to rule 1                _one[1] = ((_one[1] + 1) % size2)                if (_one[1] == 0): # see po2                    _one[0] = (_one[0] + 1) % size1            else:                print("[",a2[_one[1]],", ",                    a1[_one[0]],"] ", end=" ")Â
                # updating according to rule 1                _one[0] = ((_one[0] + 1) % size1)                if (_one[0] == 0): # see po2                    _one[1] = (_one[1] + 1) % size2Â
        elif (a1[_one[0]] + a2[_one[1]]                > a2[_two[0]] + a1[_two[1]]):            if (a2[_two[0]] < a1[_two[1]]):                print("[",a2[_two[0]],", ",a1[_two[1]],"] ",end=" ")Â
                # updating according to rule 1                _two[0] = ((_two[0] + 1) % size2)                if (_two[0] == 0): #see po2                    _two[1] = (_two[1] + 1) % size1Â
            else:                print("[",a1[_two[1]]                    ,", ",a2[_two[0]],"] ",end=" ")Â
                # updating according to rule 1                _two[1] = ((_two[1] + 1) % size1)                if (_two[1] == 0): #see po2                    _two[0] = (_two[0] + 1) % size1Â
        cnt += 1Â
# Driver Codeif __name__ == '__main__':Â
    a1= [2, 3, 4]    a2= [1, 6, 5, 8]    size1 = len(a1)    size2 = len(a2)    k = 4    printKPairs(a1, a2, size1, size2, k)Â
# This code is contributed by mohit kumar 29 |
C#
// C# program to print // the k smallest pairs // | Set 2using System;class GFG{Â
public class _pair {Â Â public int first, Â Â Â Â Â Â Â Â Â Â Â Â Â second;};Â
// Function to print the K // smallest pairsstatic void printKPairs(int []a1, int []a2,                         int size1, int size2,                         int k){  // if k is greater than   // total pairs  if (k > (size2 * size1))  {    Console.Write("k pairs don't exist\n");    return;  }Â
  // _pair _one keeps track of  // 'first' in a1 and 'second' in a2  // in _two, _two.first keeps track of  // element in the a2[] and _two.second  // in a1[]  _pair _one = new _pair();  _pair _two = new _pair();  _one.first = _one.second =   _two.first = _two.second = 0;Â
  int cnt = 0;Â
  // Repeat the above process   // till all K pairs are printed  while (cnt < k)   {    // when both the pointers are     // pointing to the same elements     // (point 3)    if (_one.first == _two.second &&         _two.first == _one.second)     {      if (a1[_one.first] <           a2[_one.second])       {        Console.Write("[" + a1[_one.first] +                       ", " + a2[_one.second] +                       "] ");Â
        // updates according to step 1        _one.second = (_one.second + 1) %                         size2;Â
        // see point 2        if (_one.second == 0)           _one.first = (_one.first + 1) %                          size1;Â
        // updates opposite to step 1        _two.second = (_two.second + 1) %                         size2;Â
        if (_two.second == 0)          _two.first = (_two.first + 1) %                          size2;      }      else      {        Console.Write("[" + a2[_one.second] +                       ", " + a1[_one.first] +                       "] ");Â
        // updates according to rule 1        _one.first = (_one.first + 1) %                        size1;Â
        // see point 2        if (_one.first == 0)           _one.second = (_one.second + 1) %                           size2;Â
        // updates opposite to rule 1        _two.first = (_two.first + 1) %                        size2;Â
        // see point 2        if (_two.first == 0)           _two.second = (_two.second + 1) %                           size1;      }    }Â
    // else update as     // necessary (point 1)    else if (a1[_one.first] +              a2[_one.second] <=              a2[_two.first] +              a1[_two.second])     {      if (a1[_one.first] <          a2[_one.second])       {        Console.Write("[" + a1[_one.first] +                       ", " + a2[_one.second] +                       "] ");Â
        // updating according to rule 1        _one.second = ((_one.second + 1) %                          size2);                 // see point 2        if (_one.second == 0)           _one.first = (_one.first + 1) %                          size1;      }      else      {        Console.Write("[" + a2[_one.second] +                      ", " + a1[_one.first] +                       "] ");Â
        // updating according to rule 1        _one.first = ((_one.first + 1) %                         size1);Â
        // see point 2        if (_one.first == 0)           _one.second = (_one.second + 1) %                           size2;      }    }    else if (a1[_one.first] +              a2[_one.second] >              a2[_two.first] +              a1[_two.second])     {      if (a2[_two.first] <           a1[_two.second])       {        Console.Write("[" + a2[_two.first] +                       ", " + a1[_two.second] +                       "] ");Â
        // updating according to rule 1        _two.first = ((_two.first + 1) %                         size2);Â
        // see point 2        if (_two.first == 0)           _two.second = (_two.second + 1) %                           size1;      }      else {        Console.Write("[" + a1[_two.second] +                       ", " + a2[_two.first] +                       "] ");Â
        // updating according to rule 1        _two.second = ((_two.second + 1) %                          size1);Â
        // see point 2        if (_two.second == 0)           _two.first = (_two.first + 1) %                          size1;      }    }    cnt++;  }}Â
// Driver Codepublic static void Main(String[] args){  int []a1 = {2, 3, 4};  int []a2 = {1, 6, 5, 8};  int size1 = a1.Length;  int size2 = a2.Length;  int k = 4;  printKPairs(a1, a2,              size1,               size2, k);}}Â
// This code is contributed by gauravrajput1 |
Javascript
<script>// Javascript program to print// the k smallest pairs// | Set 2Â
// Function to print the K// smallest pairsfunction printKPairs(a1,a2,size1,size2,k){    // if k is greater than  // total pairs  if (k > (size2 * size1))  {    document.write("k pairs don't exist\n");    return;  }    // _pair _one keeps track of  // 'first' in a1 and 'second' in a2  // in _two, _two[0] keeps track of  // element in the a2[] and _two[1]  // in a1[]  let _one = [0,0];  let _two = [0,0];    let cnt = 0;    // Repeat the above process  // till all K pairs are printed  while (cnt < k)  {    // when both the pointers are    // pointing to the same elements    // (point 3)    if (_one[0] == _two[1] &&        _two[0] == _one[1])    {      if (a1[_one[0]] <          a2[_one[1]])      {        document.write("[" + a1[_one[0]] +                         ", " + a2[_one[1]] +                         "] ");          // updates according to step 1        _one[1] = (_one[1] + 1) %                       size2;                  // see point 2        if (_one[1] == 0)          _one[0] = (_one[0] + 1) %                        size1;          // updates opposite to step 1        _two[1] = (_two[1] + 1) %                       size2;                  if (_two[1] == 0)          _two[0] = (_two[0] + 1) %                        size2;      }      else      {        document.write("[" + a2[_one[1]] +                         ", " + a1[_one[0]] +                         "] ");          // updates according to rule 1        _one[0] = (_one[0] + 1) %                      size1;                  // see point 2        if (_one[0] == 0)          _one[1] = (_one[1] + 1) %                         size2;          // updates opposite to rule 1        _two[0] = (_two[0] + 1) %                      size2;                  // see point 2        if (_two[0] == 0)                      _two[1] = (_two[1] + 1) %                         size1;      }    }          // else update as    // necessary (point 1)    else if (a1[_one[0]] +             a2[_one[1]] <=             a2[_two[0]] +             a1[_two[1]])    {      if (a1[_one[0]] <          a2[_one[1]])      {        document.write("[" + a1[_one[0]] +                         ", " + a2[_one[1]] +                         "] ");          // updating according to rule 1        _one[1] = ((_one[1] + 1) %                        size2);                  // see point 2        if (_one[1] == 0)          _one[0] = (_one[0] + 1) %                        size1;      }      else      {        document.write("[" + a2[_one[1]] +                         ", " + a1[_one[0]] +                         "] ");          // updating according to rule 1        _one[0] = ((_one[0] + 1) %                       size1);                  // see point 2        if (_one[0] == 0)          _one[1] = (_one[1] + 1) %                         size2;      }    }    else if (a1[_one[0]] +             a2[_one[1]] >             a2[_two[0]] +             a1[_two[1]])    {      if (a2[_two[0]] <          a1[_two[1]])      {        document.write("[" + a2[_two[0]] +                         ", " + a1[_two[1]] +                         "] ");          // updating according to rule 1        _two[0] = ((_two[0] + 1) %                       size2);                  // see point 2        if (_two[0] == 0)          _two[1] = (_two[1] + 1) %                         size1;      }      else {        document.write("[" + a1[_two[1]] +                         ", " + a2[_two[0]] +                         "] ");          // updating according to rule 1        _two[1] = ((_two[1] + 1) %                        size1);                  // see point 2        if (_two[1] == 0)          _two[0] = (_two[0] + 1) %                        size1;      }    }    cnt++;  }}Â
// Driver Codelet a1=[2, 3, 4];let a2=[1, 6, 5, 8];let size1 = a1.length;let size2 = a2.length;let k = 4;printKPairs(a1, a2,              size1, size2, k);     // This code is contributed by unknown2108</script> |
[1, 2] [1, 3] [1, 4] [2, 6]
Time complexity: O(K)
Space Complexity: O(1)
Using Brute Force in Python:
Approach:
One simple approach to solve this problem is to generate all possible pairs of elements from both arrays and compute their sum. Then, we can sort the pairs based on their sum and return the first k pairs. In this program, we define a function k_smallest_pairs which takes in two arrays a1 and a2, and an integer k. We first create a list of all possible pairs by using a nested list comprehension. Then, we sort the pairs based on their sum using a lambda function as the sorting key. Finally, we return the first k pairs from the sorted list using slicing.
We then call the function twice with different inputs to demonstrate its usage and output.
C++
#include <iostream>#include <vector>#include <algorithm>Â
// Function to find the k smallest pairs from two arraysstd::vector<std::pair<int, int>> kSmallestPairs(const std::vector<int>& a1, const std::vector<int>& a2, int k) {    // Create a vector to store pairs    std::vector<std::pair<int, int>> pairs;Â
    // Iterate through the elements of a1 and a2 to generate pairs    for (const int x : a1) {        for (const int y : a2) {            pairs.emplace_back(x, y);        }    }Â
    // Sort the pairs based on the sum of elements in each pair    std::sort(pairs.begin(), pairs.end(), [](const std::pair<int, int>& p1, const std::pair<int, int>& p2) {        return p1.first + p1.second < p2.first + p2.second;    });Â
    // Return the first k pairs    if (k < pairs.size()) {        pairs.resize(k);    }Â
    return pairs;}Â
int main() {Â Â Â Â // Example 1Â Â Â Â std::vector<int> a1 = {1, 7, 11};Â Â Â Â std::vector<int> a2 = {2, 4, 6};Â Â Â Â int k = 3;Â Â Â Â std::vector<std::pair<int, int>> result1 = kSmallestPairs(a1, a2, k);Â
    std::cout << "Example 1 Output: [";    for (const auto& pair : result1) {        std::cout << "(" << pair.first << ", " << pair.second << ")";        if (pair != result1.back()) {            std::cout << ", ";        }    }    std::cout << "]\n";Â
    // Example 2    a1 = {2, 3, 4};    a2 = {1, 6, 5, 8};    k = 4;    std::vector<std::pair<int, int>> result2 = kSmallestPairs(a1, a2, k);Â
    std::cout << "Example 2 Output: [";    for (const auto& pair : result2) {        std::cout << "(" << pair.first << ", " << pair.second << ")";        if (pair != result2.back()) {            std::cout << ", ";        }    }    std::cout << "]\n";Â
    return 0;} |
Python3
def k_smallest_pairs(a1, a2, k):Â Â Â Â pairs = [(x, y) for x in a1 for y in a2]Â Â Â Â pairs.sort(key=lambda p: sum(p))Â Â Â Â return pairs[:k]Â
# Example 1a1 = [1, 7, 11]a2 = [2, 4, 6]k = 3print(k_smallest_pairs(a1, a2, k))Â # Output: [(1, 2), (1, 4), (1, 6)]Â
# Example 2a1 = [2, 3, 4]a2 = [1, 6, 5, 8]k = 4print(k_smallest_pairs(a1, a2, k))Â # Output: [(2, 1), (3, 1), (4, 1), (2, 6)] |
[(1, 2), (1, 4), (1, 6)] [(2, 1), (3, 1), (4, 1), (2, 5)]
Time complexity: O(mn log mn), where m and n are the lengths of the two arrays.
Space complexity: O(mn), to store all the pairs.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
