23. Merge k Sorted Lists
Asked at 46Meta76Amazon74Apple65Microsoft64Bloomberg58Google49Deloitte100FreshWorks92Nvidia82Oracle76tcs46Salesforce45Snap45Cohesity100Netskope100X94IXL90Disney88oyo88Rivian81Moloco81Rippling75Cloudflare74MongoDB71Snowflake70SoFi69Two Sigma67Airbnb66Walmart Labs66Samsung63TikTok63Anduril60Coupang58Qualcomm58Citadel57Uber57eBay53American Express53Flipkart52ByteDance50Yandex49LinkedIn49Pinterest36DoorDash36IBM35Goldman Sachs28
Problem
Merge k sorted linked lists into one sorted list and return its head.
Example: [1→4→5, 1→3→4, 2→6] → 1→1→2→3→4→4→5→6
Constraints: k ≤ 10⁴; at most 10⁴ nodes in total.
Min-heap of the current head of each list; pop the smallest, push its successor. (Or pairwise merge, like merge sort.)
Complexity: O(N log k) for N total nodes.
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
heapify(heap)
dummy = tail = ListNode()
while heap:
_, i, node = heappop(heap) # i breaks ties (nodes aren't comparable)
tail.next = tail = node
if node.next:
heappush(heap, (node.next.val, i, node.next))
return dummy.next
ls = [make_list([1, 4, 5]), make_list([1, 3, 4]), make_list([2, 6])]
assert list_vals(Solution().mergeKLists(ls)) == [1, 1, 2, 3, 4, 4, 5, 6]
assert Solution().mergeKLists([]) is None
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val));
for (ListNode l : lists) if (l != null) pq.add(l);
ListNode dummy = new ListNode(), tail = dummy;
while (!pq.isEmpty()) {
ListNode n = pq.poll();
tail = tail.next = n;
if (n.next != null) pq.add(n.next);
}
return dummy.next;
}
}
type nodeHeap []*ListNode
func (h nodeHeap) Len() int { return len(h) }
func (h nodeHeap) Less(i, j int) bool { return h[i].Val < h[j].Val }
func (h nodeHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *nodeHeap) Push(x any) { *h = append(*h, x.(*ListNode)) }
func (h *nodeHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func mergeKLists(lists []*ListNode) *ListNode {
h := &nodeHeap{}
for _, node := range lists {
if node != nil {
heap.Push(h, node)
}
}
dummy := &ListNode{}
tail := dummy
for h.Len() > 0 {
node := heap.Pop(h).(*ListNode) // smallest head among the lists
tail.Next = node
tail = node
if node.Next != nil {
heap.Push(h, node.Next)
}
}
return dummy.Next
}