Merge K Sorted Arrays in Java

This is a classic interview question. Another similar problem is "merge k sorted lists".

This problem can be solved by using a heap. The time is O(nlog(n)).

Given m arrays, the minimum elements of all arrays can form a heap. It takes O(log(m)) to insert an element to the heap and it takes O(1) to delete the minimum element.

class ArrayContainer implements Comparable<ArrayContainer> {
	int[] arr;
	int index;
 
	public ArrayContainer(int[] arr, int index) {
		this.arr = arr;
		this.index = index;
	}
 
	@Override
	public int compareTo(ArrayContainer o) {
		return this.arr[this.index] - o.arr[o.index];
	}
}
public class KSortedArray {
	public static int[] mergeKSortedArray(int[][] arr) {
		//PriorityQueue is heap in Java 
		PriorityQueue<ArrayContainer> queue = new PriorityQueue<ArrayContainer>();
		int total=0;
 
		//add arrays to heap
		for (int i = 0; i < arr.length; i++) {
			queue.add(new ArrayContainer(arr[i], 0));
			total = total + arr[i].length;
		}
 
		int m=0;
		int result[] = new int[total];
 
		//while heap is not empty
		while(!queue.isEmpty()){
			ArrayContainer ac = queue.poll();
			result[m++]=ac.arr[ac.index];
 
			if(ac.index < ac.arr.length-1){
				queue.add(new ArrayContainer(ac.arr, ac.index+1));
			}
		}
 
		return result;
	}
 
	public static void main(String[] args) {
		int[] arr1 = { 1, 3, 5, 7 };
		int[] arr2 = { 2, 4, 6, 8 };
		int[] arr3 = { 0, 9, 10, 11 };
 
		int[] result = mergeKSortedArray(new int[][] { arr1, arr2, arr3 });
		System.out.println(Arrays.toString(result));
	}
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Hayro

    Oh, sorry. The algo should be removing only the root (min element) each time, which is O(1)

  • Hayro

    it is the time to remove it from the array

  • Sheetal

    This method doesn’t work if all array lengths are not equal.

  • Kurt Maegerle

    The problem without ArrayContainer is that, as you described, after removing from the heap you must add the “next element from the exact array which we had root from.” Knowing what the next element in the array is or what array an element came from gets pretty ugly without something like an ArrayContainer class.

    You could instead enqueue an object that has a value, an index indicated what array you are talking about, and an index indicating the current index of this array. Alternatively, it could be done with maps, but it’s even worse.

    Ultimately, I think ArrayContainer is the way to do this that makes the most sense.

  • Ankit Shah

    //you can rewrite the compareTo method like this

    public int compareTo(ArrayHolder o) {
    return this.arr[this.index] – o.arr[o.index];
    }

  • srrm

    from the javadoc for PriorityQueue – http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html

    “Implementation note: this implementation provides O(log(n)) time for the enqueing and dequeing methods (offer, poll, remove() and add);”

  • srrm

    isn’t it O(log(n)) to remove from a heap (i.e. PriorityQueue)?

  • Holden

    For example, I know we should put first elements of all arrays into the heap first, heapify it, then remove the minimum (which is root), and then we should put next element from the exact array which we had root from, to heap again, and again heapify and do this process till the end. But I cannot follow this procedure in here:

    while(!queue.isEmpty()){
    ArrayContainer ac = queue.poll();
    result[m++]=ac.arr[ac.index];

    if(ac.index < ac.arr.length-1){
    queue.add(new ArrayContainer(ac.arr, ac.index+1));
    }
    }

  • Holden

    Thank you for your great post. Could you please post a simpler solution without “ArrayContainer class”? It made it difficult to follow the solution for me. Thank you