โ† Back to Index

๐Ÿ“š Merge K Sorted Lists โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The problem involves merging K sorted linked lists into one sorted linked list. This is a classic problem that can be solved efficiently using the K-Way Merge Pattern with a min-heap.

The min-heap helps us efficiently track the smallest elements across all lists, ensuring the merged list is sorted.

๐Ÿงฑ Pattern Template

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> minHeap = new PriorityQueue<>((a, b) -> a.val - b.val);

        // Step 1: Add the head of each list to the heap
        for (ListNode node : lists) {
            if (node != null) {
                minHeap.offer(node);
            }
        }

        // Step 2: Extract the smallest element and add the next node from the same list
        ListNode dummy = new ListNode(-1);
        ListNode current = dummy;

        while (!minHeap.isEmpty()) {
            ListNode smallest = minHeap.poll();
            current.next = smallest;
            current = current.next;

            if (smallest.next != null) {
                minHeap.offer(smallest.next);
            }
        }

        return dummy.next;
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Merge K Sorted Lists

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]

Explanation:
- Add the head of each list to the heap: [1, 1, 2].
- Extract the smallest (1) and add the next node from the same list.
- Repeat until all nodes are merged into the result list.

๐Ÿ’ก Pro Tips