Find k pairs with smallest sums in two arrays | Set 2
Last Updated :
11 Jul, 2025
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
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
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 pairs
void 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 Code
int 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 2
import java.util.*;
class GFG{
static class _pair
{
int first, second;
};
// Function to print the K
// smallest pairs
static 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 Code
public 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 pairs
def 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 Code
if __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 2
using System;
class GFG{
public class _pair
{
public int first,
second;
};
// Function to print the K
// smallest pairs
static 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 Code
public 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 pairs
function 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 Code
let 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>
Output[1, 2] [1, 3] [1, 4] [2, 6]
Time complexity: O(K)
Space Complexity: O(1)
Using Brute Force :
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 arrays
std::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;
}
Java
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class Main {
// Function to find the k smallest pairs from two arrays
public static List<int[]> kSmallestPairs(int[] a1, int[] a2, int k) {
// Create a list to store pairs
List<int[]> pairs = new ArrayList<>();
// Iterate through the elements of a1 and a2 to generate pairs
for (int x : a1) {
for (int y : a2) {
pairs.add(new int[]{x, y});
}
}
// Sort the pairs based on the sum of elements in each pair
Collections.sort(pairs, new Comparator<int[]>() {
@Override
public int compare(int[] p1, int[] p2) {
return Integer.compare(p1[0] + p1[1], p2[0] + p2[1]);
}
});
// Return the first k pairs
if (k < pairs.size()) {
pairs.subList(k, pairs.size()).clear();
}
return pairs;
}
public static void main(String[] args) {
// Example 1
int[] a1 = {1, 7, 11};
int[] a2 = {2, 4, 6};
int k = 3;
List<int[]> result1 = kSmallestPairs(a1, a2, k);
System.out.print("Example 1 Output: [");
for (int i = 0; i < result1.size(); i++) {
int[] pair = result1.get(i);
System.out.print("(" + pair[0] + ", " + pair[1] + ")");
if (i != result1.size() - 1) {
System.out.print(", ");
}
}
System.out.println("]");
// Example 2
a1 = new int[]{2, 3, 4};
a2 = new int[]{1, 6, 5, 8};
k = 4;
List<int[]> result2 = kSmallestPairs(a1, a2, k);
System.out.print("Example 2 Output: [");
for (int i = 0; i < result2.size(); i++) {
int[] pair = result2.get(i);
System.out.print("(" + pair[0] + ", " + pair[1] + ")");
if (i != result2.size() - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
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 1
a1 = [1, 7, 11]
a2 = [2, 4, 6]
k = 3
print(k_smallest_pairs(a1, a2, k)) # Output: [(1, 2), (1, 4), (1, 6)]
# Example 2
a1 = [2, 3, 4]
a2 = [1, 6, 5, 8]
k = 4
print(k_smallest_pairs(a1, a2, k)) # Output: [(2, 1), (3, 1), (4, 1), (2, 6)]
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
// Custom comparer to compare tuples based on the sum of their elements
class TupleComparer : IComparer<Tuple<int, int>>
{
public int Compare(Tuple<int, int> x, Tuple<int, int> y)
{
return (x.Item1 + x.Item2).CompareTo(y.Item1 + y.Item2);
}
}
// Function to find the k smallest pairs from two arrays
static List<Tuple<int, int>> KSmallestPairs(List<int> a1, List<int> a2, int k)
{
// Create a list to store pairs
List<Tuple<int, int>> pairs = new List<Tuple<int, int>>();
// Iterate through the elements of a1 and a2 to generate pairs
foreach (int x in a1)
{
foreach (int y in a2)
{
pairs.Add(Tuple.Create(x, y));
}
}
// Sort the pairs using the custom comparer
pairs.Sort(new TupleComparer());
// Return the first k pairs
if (k < pairs.Count)
{
pairs = pairs.GetRange(0, k);
}
return pairs;
}
static void Main()
{
// Example 1
List<int> a1 = new List<int> { 1, 7, 11 };
List<int> a2 = new List<int> { 2, 4, 6 };
int k = 3;
List<Tuple<int, int>> result1 = KSmallestPairs(a1, a2, k);
Console.Write("Example 1 Output: [");
foreach (var pair in result1)
{
Console.Write($"({pair.Item1}, {pair.Item2})");
if (pair != result1.Last())
{
Console.Write(", ");
}
}
Console.WriteLine("]");
// Example 2
a1 = new List<int> { 2, 3, 4 };
a2 = new List<int> { 1, 6, 5, 8 };
k = 4;
List<Tuple<int, int>> result2 = KSmallestPairs(a1, a2, k);
Console.Write("Example 2 Output: [");
foreach (var pair in result2)
{
Console.Write($"({pair.Item1}, {pair.Item2})");
if (pair != result2.Last())
{
Console.Write(", ");
}
}
Console.WriteLine("]");
}
}
JavaScript
// Function to find the k smallest pairs from two arrays
function kSmallestPairs(a1, a2, k) {
// Create an array to store pairs
const pairs = [];
// Iterate through the elements of a1 and a2 to generate pairs
for (const x of a1) {
for (const y of a2) {
pairs.push([x, y]);
}
}
// Sort the pairs based on the sum of elements in each pair
pairs.sort((p1, p2) => p1[0] + p1[1] - p2[0] - p2[1]);
// Return the first k pairs
if (k < pairs.length) {
pairs.length = k;
}
return pairs;
}
// Example 1
const a1Example1 = [1, 7, 11];
const a2Example1 = [2, 4, 6];
const kExample1 = 3;
const resultExample1 = kSmallestPairs(a1Example1, a2Example1, kExample1);
console.log(resultExample1);
// Example 2
const a1Example2 = [2, 3, 4];
const a2Example2 = [1, 6, 5, 8];
const kExample2 = 4;
const resultExample2 = kSmallestPairs(a1Example2, a2Example2, kExample2);
console.log(resultExample2);
Output[(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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem