Find m-th smallest value in k sorted arrays in C++


In this problem, we are given k different arrays of different sizes. Our task is to find m-th smallest value in k sorted arrays. 

Problem Description: Here, we need to find m-th smallest element of the merged array of all k arrays.

Let’s take an example to understand the problem, 

Input:         m = 4

                   arr[][] = { {4 , 7},
                                    {2, 5, 6},
                                    {3, 9, 12, 15, 19}}

Output: 5

Explanation: 

Merged Sorted array : 2, 3, 4, 5, 6, 7, 9, 12, 15, 19

The 4th element is 5.

Solution approach:

A simple solution to find the m-th smallest elements is by creating a merged array and then sort the array in ascending order which will have the m-th smallest element of the array at index (m-1). Return this output value.

A more effective solution would be using the min heap data structure.

For this, we will create a min heap and insert elements from all arrays. And then m times remove the min element element from the heap and store the output to array. Then insert the next element to the heap.

Print the m-th removed item.

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

typedef pair<int, pair<int, int> > ppi;

int findMSmallestElement(vector<vector<int> > sortedArr, int m) {
   
   priority_queue<ppi, vector<ppi>, greater<ppi> > priorQueue;

   for (int i = 0; i < sortedArr.size(); i++)
      priorQueue.push({ sortedArr[i][0], { i, 0 } });
   int count = 0;
   int i = 0, j = 0;
   while (count < m && priorQueue.empty() == false) {
      ppi curr = priorQueue.top();
      priorQueue.pop();
      i = curr.second.first;
      j = curr.second.second;
      if (j + 1 < sortedArr[i].size())
         priorQueue.push( { sortedArr[i][j + 1], { i, (j + 1) } });
      count++;
   }
   return sortedArr[i][j];
}

int main() {
   
   vector<vector<int> > arr{ {4 , 7},
                         {2, 5, 6},
                         {3, 9, 12, 15, 19}};
   int m = 6;
   cout<<m<<"th smallest value in k sorted arrays is "<<findMSmallestElement(arr, m);

   return 0;
}

Output

6th smallest value in k sorted arrays is 7

Updated on: 25-Jan-2021

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements