โ† Back to Index

๐Ÿ“š K-Way Merge Pattern โ€“ Java Cheat Sheet

๐Ÿ“Œ About the Pattern

The K-Way Merge pattern helps efficiently merge K sorted lists (arrays or linked lists) into one sorted list. This generalizes the traditional 2-way merge (like in merge sort).

One popular approach uses a min-heap (priority queue):

  1. Insert the first element of each list into a min heap.
  2. Extract the smallest item from the heap and add it to the result list.
  3. Insert the next element from the list the extracted item came from (if available).
  4. Repeat until all elements are merged.

Use Case: Merging K sorted streams/logs, external sorting, median computation, etc.

๐Ÿงฑ Pattern Template

class Solution {
    public List<Integer> mergeKSortedLists(List<List<Integer>> lists) {
        PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
        List<Integer> result = new ArrayList<>();

        // Step 1: Add the first element of each list to the heap
        for (int i = 0; i < lists.size(); i++) {
            if (!lists.get(i).isEmpty()) {
                minHeap.offer(new int[]{lists.get(i).get(0), i, 0}); // [value, listIndex, elementIndex]
            }
        }

        // Step 2: Extract the smallest element and add the next element from the same list
        while (!minHeap.isEmpty()) {
            int[] smallest = minHeap.poll();
            result.add(smallest[0]);
            int listIndex = smallest[1];
            int elementIndex = smallest[2];

            // Add the next element from the same list to the heap
            if (elementIndex + 1 < lists.get(listIndex).size()) {
                minHeap.offer(new int[]{lists.get(listIndex).get(elementIndex + 1), listIndex, elementIndex + 1});
            }
        }

        return result;
    }
}

๐Ÿ“Š 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 first element of each list to the heap: [1, 1, 2].
- Extract the smallest (1) and add the next element from the same list.
- Repeat until all elements are merged into the result list.

๐Ÿ’ก Pro Tips