Related Articles

# Merge k sorted arrays | Set 2 (Different Sized Arrays)

• Difficulty Level : Medium
• Last Updated : 16 Feb, 2021

Given k sorted arrays of possibly different sizes, merge them and print the sorted output.
Examples:

```Input: k = 3
arr[][] = { {1, 3},
{2, 4, 6},
{0, 9, 10, 11}} ;
Output: 0 1 2 3 4 6 9 10 11

Input: k = 2
arr[][] = { {1, 3, 20},
{2, 4, 6}} ;
Output: 1 2 3 4 6 20 ```

We have discussed a solution that works for all arrays of same size in Merge k sorted arrays | Set 1.
A simple solution is to create an output array and 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(N Log k).
1. Create an output array.
2. Create a min heap of size k and insert 1st element in all the arrays into the heap
3. Repeat following steps while priority queue is not empty.
…..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.

## C++

 `// C++ program to merge k sorted arrays``// of size n each.``#include ``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 merges them together and prints``// the final sorted output.``vector<``int``> mergeKArrays(vector > arr)``{``    ``vector<``int``> output;` `    ``// Create a min heap with k heap nodes. Every``    ``// heap node has first element of an array``    ``priority_queue, greater > pq;` `    ``for` `(``int` `i = 0; i < arr.size(); i++)``        ``pq.push({ arr[i], { i, 0 } });` `    ``// Now one by one get the minimum element``    ``// from min heap and replace it with next``    ``// element of its array``    ``while` `(pq.empty() == ``false``) {``        ``ppi curr = pq.top();``        ``pq.pop();` `        ``// i ==> Array Number``        ``// j ==> Index in the array number``        ``int` `i = curr.second.first;``        ``int` `j = curr.second.second;` `        ``output.push_back(curr.first);` `        ``// The next element belongs to same array as``        ``// current.``        ``if` `(j + 1 < arr[i].size())``            ``pq.push({ arr[i][j + 1], { i, j + 1 } });``    ``}` `    ``return` `output;``}` `// Driver program to test above functions``int` `main()``{``    ``// Change n at the top to change number``    ``// of elements in an array``    ``vector > arr{ { 2, 6, 12 },``                              ``{ 1, 9 },``                              ``{ 23, 34, 90, 2000 } };` `    ``vector<``int``> output = mergeKArrays(arr);` `    ``cout << ``"Merged array is "` `<< endl;``    ``for` `(``auto` `x : output)``        ``cout << x << ``" "``;` `    ``return` `0;``}`

## Python

 `# merge function merge two arrays``# of different or same length``# if n = max(n1, n2)``# time complexity of merge is (o(n log(n)))` `from` `heapq ``import` `merge` `# function for meging k arrays``def` `mergeK(arr, k):``    ` `    ``l ``=` `arr[``0``]``    ``for` `i ``in` `range``(k``-``1``):``        ` `        ``# when k = 0 it merge arr``        ``# with arr here in l arr``        ``# is stored``        ``l ``=` `list``(merge(l, arr[i ``+` `1``]))``    ``return` `l` `# for printing array``def` `printArray(arr):``    ``print``(``*``arr)`  `# driver code``arr ``=``[[``2``, ``6``, ``12` `],``    ``[ ``1``, ``9` `],``    ``[``23``, ``34``, ``90``, ``2000` `]]``k ``=` `3` `l ``=` `mergeK(arr, k)` `printArray(l)`

## C#

 `// C# program to merge k sorted arrays``// of size n each. ``using` `System;``using` `System.Collections.Generic;``class` `GFG``{`` ` `    ``// This function takes an array of arrays as an``    ``// argument and all arrays are assumed to be``    ``// sorted. It merges them together and prints``    ``// the final sorted output.``    ``static` `List<``int``> mergeKArrays(List> arr)``    ``{``        ``List<``int``> output = ``new` `List<``int``>();``      ` `        ``// Create a min heap with k heap nodes. Every``        ``// heap node has first element of an array``        ``List>> pq =``          ``new` `List>>();``      ` `        ``for` `(``int` `i = 0; i < arr.Count; i++)``            ``pq.Add(``new` `Tuple<``int``,``                   ``Tuple<``int``,``int``>>(arr[i],``                                   ``new` `Tuple<``int``,``int``>(i, 0)));``            ` `        ``pq.Sort();``      ` `        ``// Now one by one get the minimum element``        ``// from min heap and replace it with next``        ``// element of its array``        ``while` `(pq.Count > 0) {``            ``Tuple<``int``,Tuple<``int``,``int``>> curr = pq;``            ``pq.RemoveAt(0);``      ` `            ``// i ==> Array Number``            ``// j ==> Index in the array number``            ``int` `i = curr.Item2.Item1;``            ``int` `j = curr.Item2.Item2;``      ` `            ``output.Add(curr.Item1);``      ` `            ``// The next element belongs to same array as``            ``// current.``            ``if` `(j + 1 < arr[i].Count)``            ``{``                ``pq.Add(``new` `Tuple<``int``,Tuple<``int``,``int``>>(arr[i][j + 1],``                                                     ``new` `Tuple<``int``,``int``>(i, j + 1)));``                ``pq.Sort();``            ``}``        ``}``        ``return` `output;``    ``}   ``    ` `  ``// Driver code``  ``static` `void` `Main()``  ``{``    ` `    ``// Change n at the top to change number``    ``// of elements in an array``    ``List> arr = ``new` `List>();``    ``arr.Add(``new` `List<``int``>(``new` `int``[]{2, 6, 12}));``    ``arr.Add(``new` `List<``int``>(``new` `int``[]{1, 9}));``    ``arr.Add(``new` `List<``int``>(``new` `int``[]{23, 34, 90, 2000}));``  ` `    ``List<``int``> output = mergeKArrays(arr);``  ` `    ``Console.WriteLine(``"Merged array is "``);``    ``foreach``(``int` `x ``in` `output)``        ``Console.Write(x + ``" "``);``  ``}``}` `// This code is contributed by divyeshrabadiya07.`
Output:
```Merged array is
1 2 6 9 12 23 34 90 2000```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up