
LeetCode 23. Merge k Sorted Lists — Java ImplementationProblemMerge k sorted linked lists into one sorted linked list.Approach 1: Min-Heap (PriorityQueue) — RecommendedUse a min-heap to always pick the smallest node among the heads of all lists.AlgorithmAdd the head of each list to a“PriorityQueue” (min-heap).Pop the smallest node, add it to the result list.If that node has a“next”, push“node.next” back into the heap.Repeat until the heap is empty.Java Code/**Definition for singly-linked list.public class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) { this.val val; }ListNode(int val, ListNode next) { this.val val; this.next next; }}*/class Solution {public ListNode mergeKLists(ListNode[] lists) {if (lists null || lists.length 0) return null;// Min-heap (PriorityQueue) to store nodes PriorityQueueListNode pq new PriorityQueue((a, b) - a.val - b.val); // Add the head of each list to the heap for (ListNode list : lists) { if (list ! null) { pq.offer(list); } } ListNode dummy new ListNode(0); ListNode current dummy; // Build the merged list while (!pq.isEmpty()) { ListNode smallest pq.poll(); current.next smallest; current current.next; // Add the next node from the same list back to heap if (smallest.next ! null) { pq.offer(smallest.next); } } return dummy.next;}}ComplexityAspect ComplexityTime O(N \log k) — N total nodes, k number of listsSpace O(k) — heap stores at most k nodesApproach 2: Divide and Conquer (Merge Sort)Merge lists pairwise, reducing the problem size by half each time.Java Codeclass Solution {public ListNode mergeKLists(ListNode[] lists) {if (lists null || lists.length 0) return null;return mergeKLists(lists, 0, lists.length - 1);}private ListNode mergeKLists(ListNode[] lists, int left, int right) { if (left right) return lists[left]; int mid left (right - left) / 2; ListNode l1 mergeKLists(lists, left, mid); ListNode l2 mergeKLists(lists, mid 1, right); return mergeTwoLists(l1, l2); } private ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummy new ListNode(0); ListNode current dummy; while (l1 ! null l2 ! null) { if (l1.val l2.val) { current.next l1; l1 l1.next; } else { current.next l2; l2 l2.next; } current current.next; } current.next (l1 ! null) ? l1 : l2; return dummy.next; }}ComplexityAspect ComplexityTime O(N \log k)Space O(\log k) — recursion stackComparisonApproach Time Space DifficultyMin-Heap O(N \log k) O(k) ⭐ Easier to implementDivide Conquer O(N \log k) O(\log k) ⭐⭐ More efficient spaceTest ExampleInput: lists [[1,4,5],[1,3,4],[2,6]]Output: [1,1,2,3,4,4,5,6]Recommendation: Use the Min-Heap approach for interviews — it’s clean, intuitive, and easy to get right under pressure. Use Divide Conquer when space optimization matters.