Tutorialspoint
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)
Priority QueueShopifyD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Handle edge cases - if the input array is null or empty, return null.

 Step 2: Create a min heap (priority queue) that orders nodes based on their values.
 Step 3: Add the first node of each non-null list to the min heap.
 Step 4: Create a dummy node to start building the result linked list.
 Step 5: While the min heap is not empty, poll the smallest node, append it to the result list.
 Step 6: After appending a node to the result, add its next node to the min heap if it exists.
 Step 7: Return the next of the dummy node as the head of the merged list.

Submitted Code :