How to Solve Merge K Sorted Lists on LeetCode
The Merge K Sorted Lists problem is a popular LeetCode and interview challenge, combining heap, divide-and-conquer, and linked list skills.
Problem Statement
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Why This Problem Matters for Interviews
This problem:
- Tests heap and merge logic in multi-list context
- Challenges you to write scalable, efficient code
- Is used in production merge operations (like external sort)
Approaches to Merge K Sorted Lists
1. Min-Heap / Priority Queue (Optimal)
Push one node from each list into a heap, pop min and add next from same list.
Time Complexity: O(N log k), N = total nodes
Space Complexity: O(k)
import heapq
def mergeKLists(lists: list) -> 'ListNode':
heap = []
for i, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, i, node))
dummy = curr = ListNode(0)
while heap:
val, i, node = heapq.heappop(heap)
curr.next = node
curr = curr.next
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))
return dummy.next
2. Divide and Conquer (Pairwise Merge)
Iteratively merge pairs of lists.
Time Complexity: O(N log k)
Space Complexity: O(1) (ignoring recursion stack)
def mergeKLists(lists: list) -> 'ListNode':
if not lists:
return None
while len(lists) > 1:
merged = []
for i in range(0, len(lists), 2):
l1 = lists[i]
l2 = lists[i+1] if i+1 < len(lists) else None
merged.append(mergeTwoLists(l1, l2))
lists = merged
return lists[0]
Key Interview Talking Points
- Why heap is more efficient than merging one-by-one
- How divide/conquer reduces comparisons
- The importance of N log k vs N*k complexity
- Handling empty lists
Big O Complexity Recap
Approach | Time Complexity | Space Complexity |
---|---|---|
Heap | O(N log k) | O(k) |
Divide/Conquer | O(N log k) | O(1) |
Pro Interview Tips
- Explain heap construction and push/pop mechanics.
- Compare both approaches in time/space.
- Practice with test cases