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:
Merge K Sorted Linked Lists using Min Heap
Next article icon

Merge k Sorted Arrays Using Min Heap

Last Updated : 23 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 the same size in Merge k sorted arrays

A simple solution is to create an output array and one by one copy all k arrays to it. Finally, sort the output array. This approach takes O(N Log N) time where N is the count of all elements.


An efficient solution is to use a heap data structure. The time complexity of the 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 the following steps while the priority queue is not empty. 
…..a) Remove the minimum element from the heap (minimum is always at the root) and store it in the output array. 
…..b) Insert the next element from the array from which the element is extracted. If the array doesn’t have any more elements, then do nothing.

Below is the implementation of the above approach:

C++
// C++ program to merge k sorted arrays // of size n each. #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 merges them together and prints // the final sorted output. vector<int> mergeKArrays(vector<vector<int> > arr) {     vector<int> output;      // 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     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<vector<int> > 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; } 
Java
/*package whatever //do not write package name here */  import java.util.ArrayList; import java.util.PriorityQueue;  public class MergeKSortedArrays {     private static class HeapNode         implements Comparable<HeapNode> {         int x;         int y;         int value;          HeapNode(int x, int y, int value)         {             this.x = x;             this.y = y;             this.value = value;         }          @Override public int compareTo(HeapNode hn)         {             if (this.value <= hn.value) {                 return -1;             }             else {                 return 1;             }         }     }      // Function to merge k sorted arrays.     public static ArrayList<Integer>     mergeKArrays(int[][] arr, int K)     {         ArrayList<Integer> result             = new ArrayList<Integer>();         PriorityQueue<HeapNode> heap             = new PriorityQueue<HeapNode>();          // Initially add only first column of elements. First         // element of every array         for (int i = 0; i < arr.length; i++) {             heap.add(new HeapNode(i, 0, arr[i][0]));         }          HeapNode curr = null;         while (!heap.isEmpty()) {             curr = heap.poll();             result.add(curr.value);              // Check if next element of curr min exists,             // then add that to heap.             if (curr.y < (arr[curr.x].length - 1)) {                 heap.add(                     new HeapNode(curr.x, curr.y + 1,                                  arr[curr.x][curr.y + 1]));             }         }          return result;     }      public static void main(String[] args)     {          int[][] arr = { { 2, 6, 12 },                             { 1, 9 },                             { 23, 34, 90, 2000 } };         System.out.println(             MergeKSortedArrays.mergeKArrays(arr, arr.length)                 .toString());     } } // This code has been contributed by Manjunatha KB 
Python
# Python code to implement the approach  import heapq  # Merge function merge two arrays # of different or same length # if n = max(n1, n2) # time complexity of merge is (o(n log(n)))  # Function for meging k arrays def mergeK(arr, k):     res = []          # Declaring min heap     h = []          # Inserting the first elements of each row     for i in range(len(arr)):         heapq.heappush(h, (arr[i][0], i, 0))              # Loop to merge all the arrays     while h:                # ap stores the row number,          # vp stores the column number         val, ap, vp = heapq.heappop(h)         res.append(val)         if vp+1 < len(arr[ap]):             heapq.heappush(h, (arr[ap][vp+1], ap, vp+1))     return res                   # Driver code if __name__ == '__main__':     arr =[[2, 6, 12 ],           [ 1, 9 ],           [23, 34, 90, 2000 ]]     k = 3     l = mergeK(arr, k)     print(*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<List<int>> 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<Tuple<int,Tuple<int,int>>> pq =          new List<Tuple<int,Tuple<int,int>>>();               for (int i = 0; i < arr.Count; i++)              pq.Add(new Tuple<int,                 Tuple<int,int>>(arr[i][0],                                  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[0];              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<List<int>> arr = new List<List<int>>();     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. 
JavaScript
// JavaScript code to implement the approach  class Node { constructor(val, row, col) { this.val = val; this.row = row; this.col = col; } }  class PriorityQueue { constructor() { this.items = []; }   enqueue(node) {     let contain = false;     for (let i = 0; i < this.items.length; i++) {         if (this.items[i].val > node.val) {             this.items.splice(i, 0, node);             contain = true;             break;         }     }     if (!contain) {         this.items.push(node);     } }  dequeue() {     return this.items.shift(); }  isEmpty() {     return this.items.length == 0; } }  // Function to merge k arrays function mergeK(arr, k) { let res = []; let pq = new PriorityQueue();   // Inserting the first elements of each row for (let i = 0; i < arr.length; i++) {     pq.enqueue(new Node(arr[i][0], i, 0)); }  // Loop to merge all the arrays while (!pq.isEmpty()) {     let node = pq.dequeue();     res.push(node.val);     if (node.col + 1 < arr[node.row].length) {         pq.enqueue(new Node(arr[node.row][node.col + 1], node.row, node.col + 1));     } } return res; }  // Driver code let arr = [[2, 6, 12], [1, 9], [23, 34, 90, 2000]]; let k = 3; let l = mergeK(arr, k); document.write(l.join(' ')); 

Output
Merged array is  1 2 6 9 12 23 34 90 2000 

Time Complexity: O(N log k) Here N is total number of elements in all input arrays.
Auxiliary Space: O(k)



Next Article
Merge K Sorted Linked Lists using Min Heap
author
kartik
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Merge two sorted arrays in Python using heapq
    Given two sorted arrays, the task is to merge them in a sorted manner. Examples: Input : arr1 = [1, 3, 4, 5] arr2 = [2, 4, 6, 8] Output : arr3 = [1, 2, 3, 4, 4, 5, 6, 8] Input : arr1 = [5, 8, 9] arr2 = [4, 7, 8] Output : arr3 = [4, 5, 7, 8, 8, 9] This problem has existing solution please refer Merge
    2 min read
  • Merge two sorted arrays in constant space using Min Heap
    Given two sorted arrays, we need to merge them with O(1) extra space into a sorted array, when N is the size of the first array, and M is the size of the second array. Example : Input: arr1[] = {10}; arr2[] = {2, 3};Output: arr1[] = {2} arr2[] = {3, 10} Input: arr1[] = {1, 5, 9, 10, 15, 20}; arr2[]
    8 min read
  • Merge K Sorted Linked Lists using Min Heap
    Given k sorted linked lists of different sizes, the task is to merge them all maintaining their sorted order. Examples: Input: K = 3, N = 4list1 = 1->3->5->7->NULLlist2 = 2->4->6->8->NULLlist3 = 0->9->10->11->NULL Output: 0->1->2->3->4->5->6->
    9 min read
  • Merge k Sorted Arrays
    Given K sorted arrays, merge them and print the sorted output. Examples: Input: K = 3, arr = { {1, 3, 5, 7}, {2, 4, 6, 8}, {0, 9, 10, 11}}Output: 0 1 2 3 4 5 6 7 8 9 10 11 Input: k = 4, arr = { {1}, {2, 4}, {3, 7, 9, 11}, {13} }Output: 1 2 3 4 7 9 11 13 Table of Content Naive - Concatenate all and S
    15+ min read
  • Sorted merge in one array
    Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Merge B into A in sorted order. Examples: Input : a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA} b[] = {16, 17, 19, 20, 22};; Output : a[] = {10, 12, 13, 14, 16, 17, 18, 19, 20, 22} One way is to merge the two
    7 min read
  • Merge two sorted arrays using Priority queue
    Given two sorted arrays A[] and B[] of sizes N and M respectively, the task is to merge them in a sorted manner. Examples: Input: A[] = { 5, 6, 8 }, B[] = { 4, 7, 8 }Output: 4 5 6 7 8 8 Input: A[] = {1, 3, 4, 5}, B] = {2, 4, 6, 8} Output: 1 2 3 4 4 5 6 8 Input: A[] = {5, 8, 9}, B[] = {4, 7, 8} Outpu
    6 min read
  • Merge two sorted arrays
    Given two sorted arrays, the task is to merge them in a sorted manner.Examples: Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8} Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8} Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8} Output: arr3[] = {4, 5, 7, 8, 8, 9} Table of Content [Naive Approach] Concaten
    10 min read
  • Merge 3 Sorted Arrays
    Given 3 arrays A[], B[], and C[] that are sorted in ascending order, the task is to merge them together in ascending order and output the array D[]. Examples: Input: A = [1, 2, 3, 4, 5], B = [2, 3, 4], C = [4, 5, 6, 7]Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7] Input: A = [1, 2, 3, 5], B = [6,
    15+ min read
  • K-th Element of Merged Two Sorted Arrays
    Given two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays. Examples: Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5Output: 6Explanation: The final sorted array is [1
    15+ min read
  • Merge Two Sorted Arrays Without Extra Space
    Given two sorted arrays a[] and b[] of size n and m respectively, the task is to merge both the arrays and rearrange the elements such that the smallest n elements are in a[] and the remaining m elements are in b[]. All elements in a[] and b[] should be in sorted order. Examples: Input: a[] = [2, 4,
    15+ 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