Solving Leetcode Interviews in Seconds with AI: Merge k Sorted Lists
Introduction
In this blog post, we will explore how to solve the LeetCode problem "23" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Example 1: Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6 Example 2: Input: lists = [] Output: [] Example 3: Input: lists = [[]] Output: [] Constraints: k == lists.length 0 <= k <= 104 0 <= lists[i].length <= 500 -104 <= lists[i][j] <= 104 lists[i] is sorted in ascending order. The sum of lists[i].length will not exceed 104.
Explanation
Here's a breakdown of the solution approach and the Python code:
- Priority Queue (Min-Heap): Use a min-heap data structure to efficiently track the smallest element across all k linked lists. The heap always provides the node with the smallest value for insertion into the merged list.
- Heap Initialization: Insert the head nodes of all non-empty linked lists into the min-heap.
Iterative Merging: Repeatedly extract the smallest node from the heap, append it to the merged list, and insert the next node from the same linked list (if it exists) back into the heap.
Runtime Complexity: O(N log k), where N is the total number of nodes and k is the number of linked lists. Storage Complexity: O(k) due to the heap.
Code
import heapq
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeKLists(lists):
"""
Merges k sorted linked lists into one sorted linked list.
Args:
lists: A list of k sorted linked lists.
Returns:
The head of the merged sorted linked list.
"""
# Create a min-heap to store the head nodes of the linked lists.
heap = []
for i in range(len(lists)):
if lists[i]:
heapq.heappush(heap, (lists[i].val, i, lists[i]))
# Create a dummy node to simplify the merging process.
dummy = ListNode(0)
tail = dummy
# Merge the linked lists.
while heap:
val, list_index, node = heapq.heappop(heap)
tail.next = node
tail = tail.next
if node.next:
heapq.heappush(heap, (node.next.val, list_index, node.next))
return dummy.next