LeetCode 23: Merge k Sorted Lists Solution

Master LeetCode problem 23 (Merge k Sorted Lists), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

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.

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 23 (Merge k Sorted Lists)?

This page provides optimized solutions for LeetCode problem 23 (Merge k Sorted Lists) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 23 (Merge k Sorted Lists)?

The time complexity for LeetCode 23 (Merge k Sorted Lists) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 23 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 23 in Java, C++, or Python.

Back to LeetCode Solutions