Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
C++ Program to Find the subarray with least average
Next article icon

C++ Program for Find k pairs with smallest sums in two arrays

Last Updated : 17 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 3  Output : [1, 2],           [1, 4],           [1, 6]  Explanation: 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]

Method 1 (Simple)  

  1. Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays.
  2. Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2))

Overall Time Complexity : O(n1 * n2 * log (n1 * n2))
Method 2 (Efficient): 
We one by one find k smallest sum pairs, starting from least sum pair. The idea is to keep track of all elements of arr2[] which have been already considered for every element arr1[i1] so that in an iteration we only consider next element. For this purpose, we use an index array index2[] to track the indexes of next elements in the other array. It simply means that which element of second array to be added with the element of first array in each and every iteration. We increment value in index array for the element that forms next minimum value pair.  

C++
// C++ program to prints first k pairs with least sum from two // arrays. #include<bits/stdc++.h>  using namespace std;  // Function to find k pairs with least sum such // that one element of a pair is from arr1[] and // other element is from arr2[] void kSmallestPair(int arr1[], int n1, int arr2[],                                    int n2, int k) {     if (k > n1*n2)     {         cout << "k pairs don't exist";         return ;     }      // Stores current index in arr2[] for     // every element of arr1[]. Initially     // all values are considered 0.     // Here current index is the index before     // which all elements are considered as     // part of output.     int index2[n1];     memset(index2, 0, sizeof(index2));      while (k > 0)     {         // Initialize current pair sum as infinite         int min_sum = INT_MAX;         int min_index = 0;          // To pick next pair, traverse for all elements         // of arr1[], for every element, find corresponding         // current element in arr2[] and pick minimum of         // all formed pairs.         for (int i1 = 0; i1 < n1; i1++)         {             // Check if current element of arr1[] plus             // element of array2 to be used gives minimum             // sum             if (index2[i1] < n2 &&                 arr1[i1] + arr2[index2[i1]] < min_sum)             {                 // Update index that gives minimum                 min_index = i1;                  // update minimum sum                 min_sum = arr1[i1] + arr2[index2[i1]];             }         }          cout << "(" << arr1[min_index] << ", "              << arr2[index2[min_index]] << ") ";          index2[min_index]++;          k--;     } }  // Driver code int main() {     int arr1[] = {1, 3, 11};     int n1 = sizeof(arr1) / sizeof(arr1[0]);      int arr2[] = {2, 4, 8};     int n2 = sizeof(arr2) / sizeof(arr2[0]);      int k = 4;     kSmallestPair( arr1, n1, arr2, n2, k);      return 0; } 

Output
(1, 2) (1, 4) (3, 2) (3, 4) 

Time Complexity : O(k*n1), where n1 represents the size of the given array.
Auxiliary Space: O(n1), where n1 represents the size of the given array.Method 3 : Using Sorting, Min heap, Map 
Instead of brute forcing through all the possible sum combinations we should find a way to limit our search space to possible candidate sum combinations.  

  1. Sort both arrays array A and array B.
  2. Create a min heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum.
  3. Initialize the heap with the minimum possible sum combination i.e (A[0] + B[0]) and with the indices of elements from both arrays (0, 0). The tuple inside min heap will be (A[0] + B[0], 0, 0). Heap is ordered by first value i.e sum of both elements.
  4. Pop the heap to get the current smallest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j). 
    • Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.
    • Go back to 4 until K times.
C++
// C++ program to Prints // first k pairs with // least sum from two arrays.  #include <bits/stdc++.h> using namespace std;  // Function to find k pairs // with least sum such // that one element of a pair // is from arr1[] and // other element is from arr2[] void kSmallestPair(vector<int> A, vector<int> B, int K) {     sort(A.begin(), A.end());     sort(B.begin(), B.end());      int n = A.size();      // Min heap which contains tuple of the format     // (sum, (i, j)) i and j are the indices     // of the elements from array A     // and array B which make up the sum.      priority_queue<pair<int, pair<int, int> >,                    vector<pair<int, pair<int, int> > >,                    greater<pair<int, pair<int, int> > > >         pq;      // my_set is used to store the indices of     // the  pair(i, j) we use my_set to make sure     // the indices doe not repeat inside min heap.      set<pair<int, int> > my_set;      // initialize the heap with the minimum sum     // combination i.e. (A[0] + B[0])     // and also push indices (0,0) along     // with sum.      pq.push(make_pair(A[0] + B[0], make_pair(0, 0)));      my_set.insert(make_pair(0, 0));      // iterate upto K     int flag=1;     for (int count = 0; count < K && flag; count++) {          // tuple format (sum, i, j).         pair<int, pair<int, int> > temp = pq.top();         pq.pop();          int i = temp.second.first;         int j = temp.second.second;          cout << "(" << A[i] << ", " << B[j] << ")"              << endl; // Extracting pair with least sum such                       // that one element is from arr1 and                       // another is from arr2          // check if i+1 is in the range of our first array A         flag=0;         if (i + 1 < A.size()) {             int sum = A[i + 1] + B[j];             // insert (A[i + 1] + B[j], (i + 1, j))             // into min heap.             pair<int, int> temp1 = make_pair(i + 1, j);              // insert only if the pair (i + 1, j) is             // not already present inside the map i.e.             // no repeating pair should be present inside             // the heap.              if (my_set.find(temp1) == my_set.end()) {                 pq.push(make_pair(sum, temp1));                 my_set.insert(temp1);             }           flag=1;         }         // check if j+1 is in the range of our second array         // B         if (j + 1 < B.size()) {             // insert (A[i] + B[j + 1], (i, j + 1))             // into min heap.              int sum = A[i] + B[j + 1];             pair<int, int> temp1 = make_pair(i, j + 1);              // insert only if the pair (i, j + 1)             // is not present inside the heap.              if (my_set.find(temp1) == my_set.end()) {                 pq.push(make_pair(sum, temp1));                 my_set.insert(temp1);             }           flag=1;         }     } }  // Driver Code. int main() {     vector<int> A = { 1 };     vector<int> B = { 2, 4, 5, 9 };     int K = 3;     kSmallestPair(A, B, K);     return 0; }  // This code is contributed by Dhairya. 

 
 


Output
(1, 2)  (1, 4)  (1, 5)

Time Complexity : O(n*logn) assuming k<=n.

Auxiliary Space: O(n), where n is the size of the given array.


Please refer complete article on Find k pairs with smallest sums in two arrays for more details!


Next Article
C++ Program to Find the subarray with least average
author
kartik
Improve
Article Tags :
  • C++ Programs
  • C++
  • DSA
  • Arrays
  • Order-Statistics
Practice Tags :
  • CPP
  • Arrays

Similar Reads

  • C++ Program to Count pairs with given sum
    Given an array of integers, and a number 'sum', find the number of pairs of integers in the array whose sum is equal to 'sum'. Examples: Input : arr[] = {1, 5, 7, -1}, sum = 6 Output : 2 Pairs with sum 6 are (1, 5) and (7, -1) Input : arr[] = {1, 5, 7, -1, 5}, sum = 6 Output : 3 Pairs with sum 6 are
    4 min read
  • C++ Program to Find a pair with the given difference
    Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78 Output: Pair Found: (2, 80) Input: arr[] = {90, 70, 20, 80, 50}, n = 45 Output: No Such Pair Recommended: Please solve it on "PRA
    4 min read
  • C++ Program for Number of pairs with maximum sum
    Given an array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i Example : Input : arr[] = {1, 1, 1, 2, 2, 2} Output : 3 Explanation: The maximum possible pair sum where i Method 1 (Naive) Traverse a loop i from 0 to n, i.e length of the array and another loop j
    3 min read
  • C++ Program to Find the subarray with least average
    Given an array arr[] of size n and integer k such that k Examples :  Input: arr[] = {3, 7, 90, 20, 10, 50, 40}, k = 3 Output: Subarray between indexes 3 and 5 The subarray {20, 10, 50} has the least average among all subarrays of size 3. Input: arr[] = {3, 7, 5, 20, -10, 0, 12}, k = 2 Output: Subarr
    3 min read
  • Smallest Pair Sum in an array
    Given an array of distinct integers arr[], the task is to find a pair which has the minimum sum and print the sum. Examples: Input: arr[] = {1, 2, 3} Output: 3 The pair (1, 2) will have the minimum sum pair i.e. 1 + 2 = 3 Input: arr[] = {3, 5, 6, 2} Output: 5 Approach: Find the minimum element from
    5 min read
  • C++ Program to Find the K-th Largest Sum Contiguous Subarray
    Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers. Examples:  Input: a[] = {20, -5, -1} k = 3 Output: 14 Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) so the
    3 min read
  • Kth smallest number in array formed by product of any two elements from two arrays
    Given two sorted arrays A[] and B[] consisting of N and M integers respectively, the task is to find the Kth smallest number in the array formed by the product of all possible pairs from array A[] and B[] respectively. Examples: Input: A[] = {1, 2, 3}, B[] = {-1, 1}, K = 4Output: 1Explanation: The a
    15+ min read
  • Find k ordered pairs in array with minimum difference d
    Given an array arr[] and two integers K and D, the task is to find exactly K pairs (arr[i], arr[j]) from the array such that |arr[i] - arr[j]| ? D and i != j. If it is impossible to get such pairs then print -1. Note that a single element can only participate in a single pair.Examples: Input: arr[]
    6 min read
  • C++ Program for Two Pointers Technique
    Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Let’s see the naive so
    4 min read
  • How to Find Common Elements in Two Arrays in C++?
    In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the common elements in two arrays in C++. Examples: Input:Arr1: {1, 2, 3, 4, 5}Arr2: {3, 4, 5, 6, 7}Output:Common Elements: 3 4
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences