Merge K Sorted Lists in Python and Java
In this tutorial, we will learn LeetCode #23: Merge K Sorted Lists in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Merge K Sorted Lists Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use min heap because it gives a clean and optimized solution.
Example input: lists = [[1,5],[2,4,7],[3,6]] Expected result: Output: [1,2,3,4,5,6,7] Explanation: Always take the smallest current node.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: lists = [[1,5],[2,4,7],[3,6]] Approach: min heap We update variables step by step until we reach: Output: [1,2,3,4,5,6,7]
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why min heap is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. lists = [[1,5],[2,4,7],[3,6]] We will solve it using min heap. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: [1,2,3,4,5,6,7] Why? Always take the smallest current node.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: [1,2,3,4,5,6,7]
Example 1
Input: lists = [[1,5],[2,4,7],[3,6]] Output: Output: [1,2,3,4,5,6,7] Explanation: Always take the smallest current node.
Example 2
Input: lists = [[2,8],[1,3,9],[4,7]] Output: [1,2,3,4,7,8,9] Explanation: Always take the smallest current node from the lists.
Python Code
Here is the complete Python solution for LeetCode #23.
import heapq
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class KSortedListMerger:
def merge_k_lists(self, lists):
heap = []
for index, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, index, node))
dummy = ListNode()
tail = dummy
while heap:
value, index, node = heapq.heappop(heap)
tail.next = node
tail = tail.next
if node.next:
heapq.heappush(heap, (node.next.val, index, node.next))
return dummy.next
def build_linked_list(values):
dummy = ListNode()
current = dummy
for value in values:
current.next = ListNode(value)
current = current.next
return dummy.next
def linked_list_to_list(head):
values = []
while head:
values.append(head.val)
head = head.next
return values
lists1 = [
build_linked_list([1, 5, 9]),
build_linked_list([2, 4, 8]),
build_linked_list([3, 6, 7]),
]
lists2 = [
build_linked_list([0, 10]),
build_linked_list([1, 3, 11]),
build_linked_list([2, 12]),
]
merger = KSortedListMerger()
print(linked_list_to_list(merger.merge_k_lists(lists1))) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(linked_list_to_list(merger.merge_k_lists(lists2))) # Output: [0, 1, 2, 3, 10, 11, 12]Java Code
Here is the complete Java solution for LeetCode #23.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
class KSortedListMerger {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> heap = new PriorityQueue<>((a, b) -> a.val - b.val);
for (ListNode node : lists) {
if (node != null) {
heap.offer(node);
}
}
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (!heap.isEmpty()) {
ListNode node = heap.poll();
tail.next = node;
tail = tail.next;
if (node.next != null) {
heap.offer(node.next);
}
}
return dummy.next;
}
private static ListNode buildList(int[] values) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
for (int value : values) {
current.next = new ListNode(value);
current = current.next;
}
return dummy.next;
}
private static List<Integer> toList(ListNode head) {
List<Integer> values = new ArrayList<>();
while (head != null) {
values.add(head.val);
head = head.next;
}
return values;
}
public static void main(String[] args) {
KSortedListMerger merger = new KSortedListMerger();
ListNode[] lists1 = new ListNode[] {
buildList(new int[] {1, 5, 9}),
buildList(new int[] {2, 4, 8}),
buildList(new int[] {3, 6, 7})
};
ListNode[] lists2 = new ListNode[] {
buildList(new int[] {0, 10}),
buildList(new int[] {1, 3, 11}),
buildList(new int[] {2, 12})
};
System.out.println(toList(merger.mergeKLists(lists1))); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
System.out.println(toList(merger.mergeKLists(lists2))); // [0, 1, 2, 3, 10, 11, 12]
}
}Time and Space Complexity
Time Complexity: O(n log k)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #23: Merge K Sorted Lists becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.