This problem can be solved using a min-heap of size k.
The min-heap will always store the next unmerged element from each of the k sorted arrays. The element with the smallest value sits at the root of the heap. We build the merged array by repeatedly popping the root from the heap. Each time we pop from the heap, we also push the next element from the same array (if one exists) onto the heap.
When the heap is empty, all elements from all arrays have been merged, and we can return the merged result.
Step 1: Initialize the heap
The first step is to initialize the heap with the first element from each of the k arrays. We iterate over each array and push a tuple containing three values onto the heap:
The element’s value
The array’s index (which array it came from)
The element’s index within that array (starting at 0)
from heapq import heappush, heappopdef mergeKLists(lists): if not lists: return None non_empty = [head for head in lists if head] if not non_empty: return None heap = [] for head in non_empty: heappush(heap, (head.val, id(head), head)) dummy = ListNode(0) current = dummy while heap: val, _, node = heappop(heap) current.next = node current = current.next if node.next: heappush(heap, (node.next.val, id(node.next), node.next)) return dummy.next
public ListNode mergeKLists(List<ListNode> lists) { if (lists == null || lists.isEmpty()) { return null; } List<ListNode> nonEmpty = new ArrayList<>(); for (ListNode head : lists) { if (head != null) { nonEmpty.add(head); } } if (nonEmpty.isEmpty()) { return null; } PriorityQueue<ListNode> heap = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val)); for (ListNode head : nonEmpty) { heap.offer(head); } ListNode dummy = new ListNode(0); ListNode current = dummy; while (!heap.isEmpty()) { ListNode node = heap.poll(); current.next = node; current = current.next; if (node.next != null) { heap.offer(node.next); } } return dummy.next;}
func mergeKLists(lists []*ListNode) *ListNode { if len(lists) == 0 { return nil } nonEmpty := []*ListNode{} for _, head := range lists { if head != nil { nonEmpty = append(nonEmpty, head) } } if len(nonEmpty) == 0 { return nil } heap := &ListNodeHeap{} for _, head := range nonEmpty { heap.Push(head) } dummy := &ListNode{Val: 0} current := dummy for heap.Len() > 0 { node := heap.Pop().(*ListNode) current.Next = node current = current.Next if node.Next != nil { heap.Push(node.Next) } } return dummy.Next}
function mergeKLists(lists: (ListNode | null)[]): ListNode | null { if (!lists || lists.length === 0) { return null; } const nonEmpty = lists.filter(head => head !== null) as ListNode[]; if (nonEmpty.length === 0) { return null; } const heap = new MinPriorityQueue<ListNode>({ priority: x => x.val }); for (const head of nonEmpty) { heap.enqueue(head); } const dummy = new ListNode(0); let current = dummy; while (!heap.isEmpty()) { const node = heap.dequeue().element; current.next = node; current = current.next; if (node.next) { heap.enqueue(node.next); } } return dummy.next;}
Step 2: Build the merged array
With the heap initialized, we can now build the merged result array. We start by creating an empty result array where we’ll append elements in sorted order.
Now, we repeatedly pop the root of the heap, which gives us the element with the smallest value among the unmerged elements from the k arrays. We append this value to our result array.
To ensure that our heap always contains the next unmerged element from each array, after popping an element, we check if there’s a next element in the same array. If there is, we push a tuple with the next element’s value, the same array index, and the incremented element index onto the heap.
When the heap is empty, all elements from all arrays have been merged, and we can return the result array.