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 = 2 arr[][] = { {1, 3, 20}, {2, 4, 6}} ; Explanation The merged array would be {1 2 3 4 6 20}. The 2nd smallest element would be 2. Output: 2
A simple solution is to create an output array and one by one copy all arrays to it. Finally, sort the output array using. This approach takes O(N Logn N) time where N is count of all elements.
An efficient solution is to use heap data structure. The time complexity of heap based solution is O(m Log k).
1. Create a min heap of size k and insert 1st element in all the arrays into the heap
2. Repeat following steps m times
…..a) Remove minimum element from heap (minimum is always at root) and store it in output array.
…..b) Insert next element from the array from which the element is extracted. If the array doesn’t have any more elements, then do nothing.
3. Print the last removed item.
CPP
// C++ program to find m-th smallest element // in the merged arrays. #include <bits/stdc++.h> using namespace std; // A pair of pairs, first element is going to // store value, second element index of array // and third element index in the array. typedef pair< int , pair< int , int > > ppi; // This function takes an array of arrays as an // argument and all arrays are assumed to be // sorted. It returns m-th smallest element in // the array obtained after merging the given // arrays. int mThLargest(vector<vector< int > > arr, int m) { // Create a min heap with k heap nodes. Every // heap node has first element of an array priority_queue<ppi, vector<ppi>, greater<ppi> > pq; for ( int i = 0; i < arr.size(); i++) pq.push({ arr[i][0], { i, 0 } }); // Now one by one get the minimum element // from min heap and replace it with next // element of its array int count = 0; int i = 0, j = 0; while (count < m && pq.empty() == false ) { ppi curr = pq.top(); pq.pop(); // i ==> Array Number // j ==> Index in the array number i = curr.second.first; j = curr.second.second; // The next element belongs to same array as // current. if (j + 1 < arr[i].size()) pq.push({ arr[i][j + 1], { i, j + 1 } }); count++; } return arr[i][j]; } // Driver program to test above functions int main() { vector<vector< int > > arr{ { 2, 6, 12 }, { 1, 9 }, { 23, 34, 90, 2000 } }; int m = 4; cout << mThLargest(arr, m); return 0; } |
Java
// This function takes an array of arrays as an // argument and all arrays are assumed to be // sorted. It returns m-th smallest element in // the array obtained after merging the given // arrays. import java.util.*; public class Main { public static int mThLargest( int [][] arr, int m) { // Create a min heap. Every // heap node has first element of an array PriorityQueue<Pair> pq = new PriorityQueue<Pair>(); for ( int i = 0 ; i < arr.length; i++) { pq.add( new Pair(arr[i][ 0 ], i, 0 )); } // Now one by one get the minimum element // from min heap and replace it with next // element of its array int count = 0 ; int i= 0 ; int j= 0 ; while (count < m && !pq.isEmpty()) { Pair curr = pq.poll(); // i ==> Array Number // j ==> Index in the array number i = curr.arrayNumber; j = curr.index; // The next element belongs to same array as current. if (j + 1 < arr[i].length) { pq.add( new Pair(arr[i][j + 1 ], i, j + 1 )); } count++; } return arr[i][j]; } // Driver Code public static void main(String[] args) { int [][] arr = { { 2 , 6 , 12 }, { 1 , 9 }, { 23 , 34 , 90 , 2000 } }; int m = 4 ; System.out.println(mThLargest(arr, m)); } } //Class to store array number and index class Pair implements Comparable<Pair> { int value; int arrayNumber; int index; // Constructor public Pair( int v, int i, int j) { value = v; arrayNumber = i; index = j; } // Compare two pair according to their values. public int compareTo(Pair o) { return this .value - o.value; } } |
Python3
# Python program to find m-th smallest element # in the merged arrays. from heapq import * # This function takes an array of arrays as an # argument and all arrays are assumed to be # sorted. It returns m-th smallest element in # the array obtained after merging the given # arrays. def mThLargest(arr, m): # Create a min heap. Every # heap node has first element of an array pq = [] for i in range ( len (arr)): heappush(pq, (arr[i][ 0 ], (i, 0 ))) # Now one by one get the minimum element # from min heap and replace it with next # element of its array count = 0 while count < m and pq: curr = heappop(pq) # i ==> Array Number # j ==> Index in the array number i = curr[ 1 ][ 0 ] j = curr[ 1 ][ 1 ] # The next element belongs to same array as current. if j + 1 < len (arr[i]): heappush(pq, (arr[i][j + 1 ], (i, j + 1 ))) count + = 1 return arr[i][j] # Driver Code arr = [[ 2 , 6 , 12 ], [ 1 , 9 ], [ 23 , 34 , 90 , 2000 ]] m = 4 print (mThLargest(arr, m)) # This code is contributed by vivekmaddheshiya205 |
C#
// C# code addition using System; using System.Collections.Generic; public class GFG { public static int MThLargest( int [][] arr, int m) { // A pair of pairs, first element is going to // store value, second element index of array // and third element index in the array. // Create a min heap with k heap nodes. Every // heap node has first element of an array List<Tuple< int , Tuple< int , int >>> pq = new List<Tuple< int , Tuple< int , int >>>(); for ( int indx = 0; indx < arr.Length; indx++) pq.Add(Tuple.Create(arr[indx][0], Tuple.Create(indx, 0))); // Now one by one get the minimum element // from min heap and replace it with next // element of its array int count = 0; int i = 0, j = 0; while (count < m && pq.Count > 0) { Tuple< int , Tuple< int , int >> curr = pq[0]; pq.RemoveAt(0); pq.Sort((a, b) => a.Item1.CompareTo(b.Item1)); // i ==> Array Number // j ==> Index in the array number i = curr.Item2.Item1; j = curr.Item2.Item2; // The next element belongs to same array as // current. if (j + 1 < arr[i].Length) pq.Add(Tuple.Create(arr[i][j + 1], Tuple.Create(i, j + 1))); count++; } return arr[i][j]; } // Driver program to test above functions static void Main() { int [][] arr = new int [][] { new int [] { 2, 6, 12 }, new int [] { 1, 9 }, new int [] { 23, 34, 90, 2000 } }; int m = 4; Console.WriteLine(MThLargest(arr, m)); } } // The code is contributed by Arushi Goel. |
Javascript
// javascript program to find m-th smallest element // in the merged arrays. const x = 3; // A pair of pairs, first element is going to // store value, second element index of array // and third element index in the array.\ // This function takes an array of arrays as an // argument and all arrays are assumed to be // sorted. It returns m-th smallest element in // the array obtained after merging the given // arrays. function mThLargest(arr, m) { // Create a min heap with k heap nodes. Every // heap node has first element of an array let pq = []; for (let i = 0; i < arr.length; i++) pq.push([arr[i][0], [i, 0 ]]); // Now one by one get the minimum element // from min heap and replace it with next // element of its array let count = 0; let i = 0, j = 0; while (count < m && pq.length > 0) { let curr = pq[0]; pq.shift(); pq.sort(); // i ==> Array Number // j ==> Index in the array number i = curr[1][0]; j = curr[1][1]; // The next element belongs to same array as // current. if (j + 1 < arr[i].length) pq.push([arr[i][j + 1], [i, j + 1]]); count++; } return arr[i][j]+x; } // Driver program to test above functions let arr = [ [ 2, 6, 12 ], [ 1, 9 ], [ 23, 34, 90, 2000 ] ]; let m = 4; console.log(mThLargest(arr, m)); // The code is contributed by Arushi Jindal. |
9
Please Login to comment...