K-th Smallest Pair Sum in given Array
Last Updated :
31 Mar, 2023
Given an array of integers arr[] of size N and an integer K, the task is to find the K-th smallest pair sum of the given array.
Examples:
Input: arr[] = {1, 5, 6, 3, 2}, K = 3
Output: 5
Explanation: The sum of all the pairs are: 1+5 = 6, 1+6 = 7, 1+3 = 4, 1+2 = 3, 5+6 = 11, 5+3 = 8, 5+2 = 7, 6+3 = 9, 6+2 = 8, 2+3 = 5. The 3rd smallest among these is 5.
Input: arr[] = {2, 4, 5, 6}, K = 6
Output: 11
Naive Approach: This is a greedy approach. We will get the sums of all possible pairs and store them in an array. Then we will sort that array in ascending order and the K-th value is the required answer.
C++
// C++ code for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to get the Kth smallest pair sum
int kthPairSum(vector<int>& arr, int K)
{
int n = arr.size();
// Vector to store the sums
vector<int> v;
// Iterating to get the sums of all
// possible pairs and store them
for(int i=0;i<n;i++)
{
for (int j=i+1; j<n; j++)
{
v.push_back(arr[i]+arr[j]);
}
}
// Sorting the new vector
sort(v.begin(),v.end());
// Returning kth element
return v[K-1];
}
// Driver code
int main()
{
vector<int> arr = { 1, 5, 6, 3, 2 };
int K = 3;
cout << kthPairSum(arr, K);
return 0;
}
// This code is contributed by Utkarsh.
Java
import java.util.*;
public class Main
{
// Function to get the Kth smallest pair sum
static int kthPairSum(List<Integer> arr, int K)
{
int n = arr.size();
// Vector to store the sums
List<Integer> v = new ArrayList<>();
// Iterating to get the sums of all
// possible pairs and store them
for(int i=0;i<n;i++)
{
for (int j=i+1; j<n; j++)
{
v.add(arr.get(i) + arr.get(j));
}
}
// Sorting the new vector
Collections.sort(v);
// Returning kth element
return v.get(K-1);
}
// Driver code
public static void main(String[] args)
{
List<Integer> arr = new ArrayList<>(Arrays.asList(1, 5, 6, 3, 2));
int K = 3;
System.out.println(kthPairSum(arr, K));
}
}
Python3
# Python code for above approach
# Function to get the Kth smallest pair sum
def kthPairSum(arr, K):
n = len(arr)
# Vector to store the sums
v = []
# Iterating to get the sums
# of all possible pairs and store them
for i in range(0, n):
for j in range(i + 1, n):
v.append(arr[i] + arr[j])
# Sorting the new vector
v.sort()
# Returning kth element
return v[K - 1]
# Driver code
arr = [1, 5, 6, 3, 2]
K = 3
print(kthPairSum(arr, K))
C#
// C# code addition
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
// Function to get the Kth smallest pair sum
public static int KthPairSum(List<int> arr, int K)
{
int n = arr.Count;
// List to store the sums
List<int> v = new List<int>();
// Iterating to get the sums of all
// possible pairs and store them
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
v.Add(arr[i] + arr[j]);
}
}
// Sorting the new list
v.Sort();
// Returning kth element
return v[K - 1];
}
// Driver code
public static void Main()
{
List<int> arr = new List<int> { 1, 5, 6, 3, 2 };
int K = 3;
Console.WriteLine(KthPairSum(arr, K));
}
}
// The code is contributed by Arushi Goel.
JavaScript
// javascript code for above approach
// Function to get the Kth smallest pair sum
function kthPairSum(arr, K)
{
let n = arr.length;
// Vector to store the sums
let v = [];
// Iterating to get the sums of all
// possible pairs and store them
for(let i=0;i<n;i++)
{
for (let j=i+1; j<n; j++)
{
v.push(arr[i]+arr[j]);
}
}
// Sorting the new vector
v.sort();
// Returning kth element
return v[K-1]+1;
}
// Driver code
let arr = [ 1, 5, 6, 3, 2 ];
let K = 3;
console.log(kthPairSum(arr, K));
// This code is contributed by Arushi Jindal.
Time Complexity: O (N2 * log(N2))
Auxiliary Space: O(N2)
Efficient Approach: The concept of this approach is based on max-heap. We will be implementing a max heap of size K. Follow the steps mentioned below:
- Start iterating the array from i = 0 to i = N-2.
- For every i iterate from j = i+1 to j = N-1.
- Get the sum of this (i, j) pair and insert it in the max heap.
- If the heap is full then compare the top element of the heap with this sum.
- If the value of the top element is greater then replace that with the new sum.
- When the iteration is over the topmost element of the max-heap is the K-th smallest pair sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to get the Kth smallest pair sum
int kthPairSum(vector<int>& arr, int K)
{
int n = arr.size();
// Priority queue to implement max-heap
priority_queue<int> pq;
// Loop to calculate all possible pair sum
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// Variable to store the sum
int temp = arr[i] + arr[j];
// If the heap is full
if (pq.size() == K) {
// If the top element is greater
if (pq.top() > temp) {
pq.pop();
pq.push(temp);
}
}
else
pq.push(temp);
}
}
// Return the Kth smallest value
return pq.top();
}
// Driver code
int main()
{
vector<int> arr = { 1, 5, 6, 3, 2 };
int K = 3;
cout << kthPairSum(arr, K);
return 0;
}
Java
// Java code for the above approach
import java.util.*;
class GFG {
// Function to get the Kth smallest pair sum
static int kthPairSum(int[] arr, int K)
{
int n = arr.length;
// Priority queue to implement max-heap
// Creating empty priority queue
PriorityQueue<Integer> pq
= new PriorityQueue<Integer>(
Collections.reverseOrder());
// Loop to calculate all possible pair sum
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// Variable to store the sum
int temp = arr[i] + arr[j];
// If the heap is full
if (pq.size() == K) {
// If the top element is greater
if (pq.peek() > temp) {
pq.poll();
pq.add(temp);
}
}
else
pq.add(temp);
}
}
// Return the Kth smallest value
return pq.peek();
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 1, 5, 6, 3, 2 };
int K = 3;
System.out.println(kthPairSum(arr, K));
}
}
// This code is contributed by Potta Lokesh
Python3
from queue import PriorityQueue
# Function to get the Kth smallest pair sum
def kthPairSum(arr, K):
n = len(arr);
# Priority queue to implement max-heap
pq = PriorityQueue()
# Loop to calculate all possible pair sum
for i in range(n - 1):
for j in range(i + 1, n):
# Variable to store the sum
temp = arr[i] + arr[j];
# If the heap is full
if (pq.qsize() == K):
# If the top element is greater
if (pq.queue[-1] > temp):
pq.get();
pq.put(temp);
else:
pq.put(temp);
# Return the Kth smallest value
return pq.queue[0];
# Driver code
arr = [ 1, 5, 6, 3, 2 ];
K = 3;
print(kthPairSum(arr, K));
# This code is contributed by saurabh_jaiswal.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to get the Kth smallest pair sum
static int kthPairSum(int[] arr, int K)
{
int n = arr.Length;
// Priority queue to implement max-heap
// Creating empty priority queue
List<int> pq = new List<int>();
// Loop to calculate all possible pair sum
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// Variable to store the sum
int temp = arr[i] + arr[j];
// If the heap is full
if (pq.Count == K) {
// If the top element is greater
if (pq[0] > temp) {
pq.Remove(0);
pq.Add(temp);
}
}
else
pq.Add(temp);
}
}
// Return the Kth smallest value
return pq[0]-1;
}
// Driver Code
public static void Main()
{
int[] arr = { 1, 5, 6, 3, 2 };
int K = 3;
Console.Write(kthPairSum(arr, K));
}
}
// This code is contributed by avijitmondal1998.
JavaScript
<script>
// Javascript code for the above approach
// Function to get the Kth smallest pair sum
function kthPairSum(arr, K)
{
let n = arr.length;
// Priority queue to implement max-heap
pq = [];
// Loop to calculate all possible pair sum
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
// Variable to store the sum
let temp = arr[i] + arr[j];
// If the heap is full
if (pq.length == K) {
// If the top element is greater
if (pq[0] > temp) {
pq.shift();
pq.push(temp);
pq.sort((a, b) => b - a);
}
}
else
{pq.push(temp);
pq.sort((a, b) => b - a);}
}
}
// Return the Kth smallest value
return pq[0];
}
// Driver code
let arr = [ 1, 5, 6, 3, 2 ];
let K = 3;
document.write(kthPairSum(arr, K));
// This code is contributed by Pushpesh raj
</script>
Time Complexity: O(N2 * logK)
Auxiliary Space: O(K)
Similar Reads
Find k pairs with smallest sums in two arrays Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[] Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3Output : [1, 2], [1, 4], [1, 6]Ex
15+ min read
Find k pairs with smallest sums in two arrays | Set 2 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 e
15+ min read
Find the smallest contiguous sum pair in an Array Given an array arr[] containing N distinct integers, the task is to find a contiguous pair such that the sum of both elements in the pair is minimum. Examples: Input: arr[] = {1, 2, 3, 4} Output: (1, 2) Explanation: Here, contiguous pairs with their sum are (1, 2) = 3, (2, 3) = 5, (3, 4) = 7 and the
5 min read
Find m-th smallest value in k sorted arrays Given k sorted arrays of possibly different sizes, find m-th smallest value in the merged array.Examples: Input: m = 5 arr[][] = { {1, 3}, {2, 4, 6}, {0, 9, 10, 11}} ; Output: 4 Explanation The merged array would be {0 1 2 3 4 6 9 10 11}. The 5-th smallest element in this merged array is 4. Input: m
8 min read
Javascript Program for Find k pairs with smallest sums in two arrays Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3Output : [1, 2], [1, 4], [1, 6]Exp
3 min read