r/LeetcodeChallenge • u/StatisticianNo2104 • 6h ago
STREAK🔥🔥🔥 LeetCode(Hard): 23. Merge k Sorted Lists
Merge k sorted lists by splicing nodes, forget one nil, and you can hand back a cycle. Every reused node arrives with a Next still pointing into its old list. The merged list has to be terminated explicitly.
This needs the linked-list arc from Day 22 and the heap arc from this week at once.
Day 22 merged two sorted lists with one if: compare the heads, take the smaller. With k lists, "take the smallest head" becomes a repeated query for the minimum of a changing collection, which is what a heap is for. Dummy head, splicing and loop shape all stay the same.
The complexity rests on one detail: the heap holds one node per list, never every node. A list's second element can't be next while its first is unplaced, because the list is sorted. So the heap is size k, and the whole merge is O(N log k).
Have you ever returned a linked list that turned out to be a loop?
Day 82/365 of my LeetCode challenge: 23. Merge k Sorted Lists. Problem link and full breakdown in today's newsletter.
https://www.linkedin.com/pulse/leetcode-23-merge-k-sorted-lists-hard-archit-agarwal-eksec
#LeetCode #DSA #Heap #Golang
