VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merge-k-sorted-arrays/

⇱ Merge Sorted Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge Sorted Arrays

Last Updated : 18 Oct, 2025

Given a 2D matrix, mat[][] consisting of sorted arrays, where each row is sorted in non-decreasing order, find a single sorted array that contains all the elements from the matrix.

Examples:

Input: mat[][] = [[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]
Explanation: Merging all elements from the 3 sorted arrays and sorting them results in: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].

Input: mat[][] = [[1, 2, 3, 4], [2, 2, 3, 4], [5, 5, 6, 6], [7, 8, 9, 9]]
Output: [1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9, 9] 
Explanation: Merging all elements from the 4 sorted arrays and sorting them results in:[1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9, 9] .

[Naive Approach] Concatenate all and Sort

The idea is to merges sorted arrays by first flattening all the arrays into a single one-dimensional vector. Then sorts this combined vector using the standard sorting algorithm (sort() from the STL). This ensures the final output is a fully sorted array containing all elements from the input arrays.


Output
0 1 2 3 4 5 6 7 8 9 10 11 

Time Complexity: O(n log(n)), where n is total number of elements
Auxiliary Space: O(1)

[Expected Approach 1] Using Merge Sort - Works Better for Equal Sized Arrays

The idea is to use the Divide and Conquer approach, similar to Merge Sort. We keep dividing the given sorted arrays into smaller groups until we are left with single array. Then, we start merging these single arrays upward in sorted order, gradually combining them until one fully sorted array remains.


Output
0 1 2 3 4 5 6 7 8 9 10 11 

Time Complexity: O(n*log⁡k), k is number of rows and n is total number of elements.
Auxiliary Space: O(n)

[Expected Approach 2] Using Min-Heap - Works better for Different Sized Arrays

The idea is to merge sorted arrays using a Min Heap. We start by inserting the first element of each array into the heap. The smallest element is always at the top, so we remove it and add it to the output array. Then we insert the next element from the same array into the heap. We repeat this process until the heap is empty. This ensures that we always pick the smallest available element, producing a fully sorted merged array efficiently.


Output
0 1 2 3 4 5 6 7 8 9 10 11 

Time Complexity: O(n*log(k)), k is number of rows and n is total number of elements.
Auxiliary Space: O(k)

Comment