23. Merge k Sorted Lists

Explanation:

To merge k sorted lists, we can use a priority queue to efficiently merge the lists together. We will continuously extract the smallest element among the heads of all lists and add it to the merged list. By doing so, we can maintain the sorted order of the merged list.

  1. Create a priority queue to store the heads of all lists based on their values.
  2. Initialize the priority queue with the heads of all lists.
  3. While the priority queue is not empty, extract the smallest element from the priority queue.
    • Add the extracted element to the merged list.
    • If the extracted element has a next node, add the next node to the priority queue.
  4. Return the merged list.

Time Complexity: Let n be the total number of elements in all lists. The time complexity is O(n log k), where k is the number of lists.

Space Complexity: The space complexity is O(k) for the priority queue.

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
        for (ListNode node : lists) {
            if (node != null) {
                pq.offer(node);
            }
        }
        
        ListNode dummy = new ListNode(-1);
        ListNode current = dummy;
        
        while (!pq.isEmpty()) {
            ListNode node = pq.poll();
            current.next = node;
            current = current.next;
            
            if (node.next != null) {
                pq.offer(node.next);
            }
        }
        
        return dummy.next;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.