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 linked list: 1->1->2->3->4->4->5->6
Example 2:
Input: lists = [] Output: []
Example 3:
Input: lists = [[]] Output: []
Constraints:
k == lists.length0 <= k <= 1040 <= lists[i].length <= 500-104 <= lists[i][j] <= 104lists[i] is sorted in ascending order.lists[i].length will not exceed 104.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have several separate stacks of playing cards, and each stack is already sorted from smallest to largest. The brute force strategy involves gathering every single card from every stack into one big pile, and then sorting the entire pile from scratch to create one single sorted stack.
Here's how the algorithm would work step-by-step:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_k_lists(lists):
collected_values = []
# Gather all items from every list into one group because we need to process them together
for current_list in lists:
current_node = current_list
while current_node is not None:
collected_values.append(current_node.val)
current_node = current_node.next
# Sort the combined group from scratch since we are ignoring original list ordering
collected_values.sort()
dummy_head = ListNode(0)
current_tail = dummy_head
# Connect sorted items together into one final linked list representing the final output
for item_value in collected_values:
current_tail.next = ListNode(item_value)
current_tail = current_tail.next
return dummy_head.nextInstead of comparing every single starting element all at once, the optimal approach uses a priority organizing tool to always track the smallest available items. By constantly pulling out the absolute smallest remaining item and adding the next item from that same group, we can build the final combined list smoothly and efficiently.
Here's how the algorithm would work step-by-step:
import heapq
class Solution:
def mergeKLists(self, list_of_linked_lists):
dummy_head_node = ListNode(0)
current_tail_node = dummy_head_node
min_heap_container = []
for list_index, starting_node in enumerate(list_of_linked_lists):
if starting_node:
heapq.heappush(min_heap_container, (starting_node.val, list_index, starting_node))
# A heap tracks the global minimum among all lists, guaranteeing efficient extraction.
while min_heap_container:
minimum_value, list_index, current_node = heapq.heappop(min_heap_container)
current_tail_node.next = current_node
current_tail_node = current_tail_node.next
# Advancing to the next node in the same list ensures we maintain continuity of sorted elements.
if current_node.next:
next_node_to_add = current_node.next
heapq.heappush(min_heap_container, (next_node_to_add.val, list_index, next_node_to_add))
# Returning the next pointer bypasses the dummy node to give the merged list start.
return dummy_head_node.next| Case | How to Handle |
|---|---|
| The input list of lists is completely empty or null | Return a null pointer immediately since there are no linked lists to merge |
| The array contains lists that are all empty or null | The min-heap or divide-and-conquer approach safely ignores null nodes and correctly evaluates remaining valid nodes |
| The input array contains only a single linked list | Return the head of that single list directly without performing any unnecessary merging operations |
| Linked lists contain negative numbers, zeros, and positive values mixed together | Value comparisons in the priority queue handle signed integers naturally based on their numeric magnitude |
| Multiple linked lists contain identical duplicate values | The min-heap extracts nodes stably or handles ties gracefully without breaking the sorted invariant |
| Extremely large number of lists k with very long individual lengths | Using a min-heap or divide-and-conquer strategy ensures optimal time complexity of N log k instead of linear scans |
| All lists are already exhausted except for one remaining long list | The algorithm processes the final stream of elements efficiently until the heap is completely empty |
| Memory constraints in languages like C++ or Java regarding node allocation and pointer management | Reuse existing node references from the input lists rather than instantiating new nodes to maintain O(1) auxiliary space |