You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
lists = [[1,4,5],[1,3,4],[2,6]][1,1,2,3,4,4,5,6]lists = [[1,2],[0,3]][0,1,2,3]poll() the minimum node from the heapnode.next != null, push node.next into the heapdummy.nextWe maintain a min-heap of size ≤ k — one candidate from each list. Each poll() retrieves the globally smallest remaining node in O(log k). After appending it, we push its successor (if any) so each list always has exactly one representative in the heap. Total nodes processed = N, each heap operation costs O(log k), giving O(N log k).
Merging the lists one by one into the result costs O(k) times n in total. A min heap always knows the smallest head.
Put the head of each list into a min heap. Pop the smallest node, attach it to the result, and push its next node if it exists. Repeat until the heap is empty.
A heap of size k holds one candidate from each list. Each pop gives the next smallest node.
Run the animation above on your own input, or watch the 1:10 video explanation of Merge K Sorted Lists with a dry run and Java code.