Looking at this problem, I need to merge k sorted linked lists into one sorted linked list. Let me solve this step by step.
Approach
I'll use a divide-and-conquer approach (similar to merge sort) to efficiently merge the k lists:
- If there are no lists or only one list, handle the base cases
- Use a recursive approach to merge pairs of lists
- Continue until only one merged list remains
Solution
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists:
return None
# Filter out empty lists
non_empty_lists = [lst for lst in lists if lst]
if not non_empty_lists:
return None
return self.mergeLists(non_empty_lists, 0, len(non_empty_lists) - 1)
def mergeLists(self, lists, start, end):
# Base case: single list
if start == end:
return lists[start]
# Base case: two lists
if start + 1 == end:
return self.mergeTwoLists(lists[start], lists[end])
# Divide and conquer
mid = (start + end) // 2
left = self.mergeLists(lists, start, mid)
right = self.mergeLists(lists, mid + 1, end)
return self.mergeTwoLists(left, right)
def mergeTwoLists(self, l1, l2):
# Create dummy head for easier handling
dummy = ListNode(0)
current = dummy
# Merge the two lists
while l1 and l2:
if l1.val <= l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
# Append remaining nodes
if l1:
current.next = l1
if l2:
current.next = l2
return dummy.next
Alternative Approach (Using Min Heap)
import heapq
class Solution:
def mergeKLists(self, lists):
if not lists:
return None
# Create a min heap
heap = []
# Add first node from each list to heap
for i, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, i, node))
# Create dummy head
dummy = ListNode(0)
current = dummy
# Process heap
while heap:
val, list_idx, node = heapq.heappop(heap)
current.next = node
current = current.next
# Add next node from the same list to heap
if node.next:
heapq.heappush(heap, (node.next.val, list_idx, node.next))
return dummy.next
Step-by-step trace for Example 1:
Input: [[1,4,5],[1,3,4],[2,6]]
-
Convert to linked lists:
- List 1: 1→4→5
- List 2: 1→3→4
- List 3: 2→6
-
Using divide-and-conquer:
- Merge lists[0] and lists[1]: 1→1→3→4→4→5
- Merge result with lists[2]: 1→1→2→3→4→4→5→6
-
Final result: 1→1→2→3→4→4→5→6
Complexity Analysis
Divide-and-Conquer Approach:
- Time: O(N log k) where N is total number of nodes, k is number of lists
- Space: O(log k) for recursion stack
Min Heap Approach:
- Time: O(N log k)
- Space: O(k) for the heap
Both approaches are efficient, but the divide-and-conquer approach is often preferred as it doesn't require additional data structures beyond the recursion stack.