
Problem
Solution
Submissions
Merge K Sorted Lists
Certification: Advanced Level
Accuracy: 100%
Submissions: 2
Points: 15
Write a Java program to merge k sorted linked lists into one sorted linked list. You need to use a priority queue (min heap) to efficiently merge these lists.
Example 1
- Input: lists = [[1,4,5],[1,3,4],[2,6]]
- Output: [1,1,2,3,4,4,5,6]
- Explanation: We have 3 sorted linked lists: [1->4->5], [1->3->4], and [2->6]. When merged, the resulting linked list is [1->1->2->3->4->4->5->6].
Example 2
- Input: lists = []
- Output: []
- Explanation: The input is an empty array, so there are no lists to merge.
Constraints
- k == lists.length
- 0 <= k <= 10^4
- 0 <= lists[i].length <= 500
- -10^4 <= lists[i][j] <= 10^4
- lists[i] is sorted in ascending order
- The sum of lists[i].length will not exceed 10^4
- Time Complexity: O(N log k) where N is the total number of nodes and k is the number of linked lists
- Space Complexity: O(k)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a priority queue (min heap) to always get the smallest node among the k lists
- Initialize the priority queue with the first node of each list
- Keep polling the smallest node from the priority queue and adding it to the result list
- After polling a node, add its next node to the priority queue if it exists
- Continue until the priority queue is empty
- Handle edge cases like empty lists or lists with null values