Problem
Merge $k$ sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
1 |
|
Explanation 1
-
We can use divide and conquer method to solve this problem. For example, if we have 6
ListNode
, then we can solve ListNode1 with ListNode4, ListNode2 with ListNode5, ListNode3 with ListNode6. -
Then, we have 3
ListNode
need to sort. We then sort ListNode1 with ListNode3. -
Then, we have 2
ListNode
need to sort. We then sort ListNode1 with ListNode2. -
Finally, we return the result of ListNode1.
-
Since there are $k$ ListNode in the array, similarly to merge sort, we divide $k$ ListNode takes $\log(k)$ time, and there are total of $kn$ nodes to compare, so the total time complexity is $kn\log(k)$. The space complexity is $log(k)$ because of the recursive stack.
Solution 1
1 |
|
Explanation 2
-
We can create a min-heap by using the PriorityQueue data structure to store all ListNode. If there are $k$ ListNode inside the input array, then we store all $k$ ListNode. They are sorted by their first Node value.
-
We create a
res
ListNode, then extract the minimum ListNode and put it’s value into theres
ListNode. If the extracted ListNode’s next node is not empty, put it back to the priority queue. Repeat this process until the priority queue is empty. -
Finally return the
res
ListNode. -
Since there are $k$ ListNode in the array, and there are $n$ ListNode in each ListNode, so there are total of $kn$ elements in the array. Because each element adding to the queue costs $log(k)$ time, so the total time complexity is $kn\log(k)$. The space complexity is $O(k)$ because of the min-heap size will have maximum $k$ ListNodes.
Solution 2
1 |
|