Question
Given k sorted arrays, merge them into a single sorted array.
eg.
merge({{1, 4, 7},{2, 5, 8},{3, 6, 9}}) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Once you think that you’ve solved the problem, click below to see the solution.
As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.
Solution
How was that problem? You can check out the solution in the video below.
Here is the source code for the solution shown in the video:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
private class QueueNode implements Comparable<QueueNode> { int array, index, value; public QueueNode(int array, int index, int value) { this.array = array; this.index = index; this.value = value; } public int compareTo(QueueNode n) { if (value > n.value) return 1; if (value < n.value) return -1; return 0; } } public int[] merge(int[][] arrays) { PriorityQueue<QueueNode> pq = new PriorityQueue<QueueNode>(); int size = 0; for (int i = 0; i < arrays.length; i++) { size += arrays[i].length; if (arrays[i].length > 0) { pq.add(new QueueNode(i, 0, arrays[i][0]); } } int[] result = new int[size]; for (int i = 0; !pq.isEmpty(); i++) { QueueNode n = pq.poll(); result[i] = n.value; int newIndex = n.index + 1; if (newIndex < arrays[n.array].length) { pq.add(new QueueNode(n.array, newIndex, arrays[n.array][newIndex]); } } return result; } |
Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.