881429. Merge k Sorted Arrays
Medium
Merge k Sorted Arrays
Slug: merge-k-sorted-arrays--151335
Difficulty: Medium
Id: 881429
Topic Tags: Arrays, Sorting, Heap, Data Structures, Algorithms
Company Tags: VMWare, Flipkart, Amazon, Microsoft, Citrix
Summary
Given k sorted arrays of size n each, the task is to merge them into a single sorted array. The input arrays are already sorted in ascending order and we need to merge them efficiently.
Detailed Explanation
To solve this problem, we can use a priority queue (min heap) where each element from the k arrays is pushed one by one. We keep track of the smallest element in the heap which represents the first element in the merged array. Once an element is popped out from the heap and added to the result array, we push the next element from the same array back into the heap.
Here's a step-by-step breakdown:
- Create a min-heap (priority queue) to store elements from the k arrays.
- Initialize the result array with size
n * k. - For each of the k arrays:
- Push all elements from the array into the min-heap.
- While the heap is not empty:
- Pop the smallest element from the heap and add it to the result array.
- If the popped element's index plus one is within the bounds of its original array, push the next element from that array into the heap.
- Return the merged array.
Time complexity: O(k * n log k) where k is the number of arrays and n is the size of each array.
Space complexity: O(k * n) for storing the result array.
Optimized Solutions
Java
import java.util.PriorityQueue;
public class MergeKSortedArrays {
public static int[] merge(int[][] arrs) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
int[] res = new int[arrs.length * arrs[0].length];
int idx = 0;
for (int[] arr : arrs) {
pq.offer(arr[0]);
}
while (!pq.isEmpty()) {
res[idx++] = pq.poll();
if (idx < arrs[0].length) {
int next = arrs[0][idx];
for (int i = 1; i < arrs.length; i++) {
if (i < arrs[i].length && arrs[i][idx] <= next) {
pq.offer(arrs[i][idx]);
break;
}
}
}
}
return res;
}
}