Merge k Sorted Linked Lists into One Sorted List

Day - 82 Merge K Sorted Lists The problem - Given an array of k linked lists, each linked list is sorted in ascending order. Merge all the linked lists into one sorted linked list and return it. Brute Force - Collect all nodes from all lists into an array, sort the array, and create a new linked list from sorted values. This gives O(N log N) time complexity where N = total number of nodes, but requires O(N) extra space for the array. Approach Used - •) Create PriorityQueue<ListNode> (min heap) with comparator (a, b) -> a.val - b.val. •) Add the head of each non-null list to the heap. •) Create dummy node and res pointer for building result list. •) While heap is not empty, 1 - Poll the smallest node curr from heap. 2 - Attach curr to result list, res.next = curr. 3 - Move result pointer, res = res.next. 4 - If curr.next is not null, add it to heap. •) Return dummy.next. Complexity - Time - O(N log k), N = total number of nodes across all lists, processing N nodes, O(N), and each heap operation O(log k). Space - O(k), heap stores at most k elements. Note - Use a min heap to efficiently perform k-way merge. At each step, extract the minimum node from the heap (smallest among all list heads), add it to result, and insert its next node back into the heap. This maintains the invariant that the heap always contains the current smallest unprocessed node from each list. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories