Taro Logo

Merge k Sorted Lists

Hard
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+40
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.7K views
Topics:
Linked ListsArraysGreedy Algorithms

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.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.

Solution


Clarifying Questions

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:

  1. Can the input array of linked lists be empty, or can some of the individual linked lists themselves be empty or null?
  2. What is the range of values stored within the nodes of the linked lists (e.g., standard 32-bit integers, or could they include negative numbers)?
  3. Should the merge be performed in-place by mutating the existing nodes, or is it expected that we construct a brand new linked list?
  4. How should duplicate values across different linked lists be handled in the merged output?
  5. Is the total number of linked lists ($k$) and the total number of nodes across all lists constrained such that we need to worry about memory limits or integer overflow?

Brute Force Solution

Approach

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:

  1. Gather all the lists of items provided.
  2. Look at every single item across all of the lists and collect them together into one large, combined group.
  3. Ignore the fact that the original lists were already sorted.
  4. Take the large combined group of items and sort the whole thing from the very beginning to the very end.
  5. Once everything is arranged in order from smallest to largest, connect the items together to form one final sorted list.

Code Implementation

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.next

Big(O) Analysis

Time Complexity
O(N log N) – To find the time complexity, let N be the total number of nodes across all the linked lists combined. The brute force strategy first visits every single node to gather them into one large collection, taking O(N) time. Next, it sorts this entire collection of N elements using a standard comparison-based sorting algorithm, which requires O(N log N) time. The cost is entirely driven by this sorting step because traversing the nodes is asymptotically smaller. Combining these steps yields approximately N + N log N operations, which simplifies to O(N log N).
Space Complexity
O(N) – The brute force strategy requires gathering every single item from all the separate lists into one large, combined group or temporary list before sorting. If we define N as the total number of elements across all k lists, this combined group must allocate memory to store all N elements simultaneously. Therefore, the extra memory used by this temporary data structure scales directly with the total input size, leading to a linear auxiliary space complexity of O(N).

Optimal Solution

Approach

Instead 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:

  1. Gather the starting item from every single sorted list.
  2. Put all of these starting items into a special organizing container that automatically keeps the smallest item right at the front.
  3. Repeatedly look at the front of your container to find the single smallest item overall.
  4. Take that smallest item and attach it to the end of your growing final combined list.
  5. Check the group that the item came from to see if there is another item waiting right behind it.
  6. If a next item exists in that group, place it into your organizing container so it can be considered.
  7. Repeat the process of taking the smallest item and bringing in its successor until all groups are completely empty.
  8. Once everything has been processed, your final combined list is fully assembled and sorted from start to finish.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(N log k) – The total input size is N, representing the total number of nodes across all k sorted lists. In our priority organizing container, which is implemented as a min-heap, we insert and extract nodes dynamically. Because the heap never holds more than k elements at any given time, each heap operation takes O(log k) time. Since we perform this insertion and extraction process for every single one of the N nodes, the total operations approximate N multiplied by log k. This scales directly to an overall time complexity of O(N log k).
Space Complexity
O(k) – The auxiliary space is driven by the organizing container, which is a min-heap used to track the current smallest item from each of the k sorted lists simultaneously. At any given time, this heap stores at most one element from each of the k lists, meaning its size is directly proportional to k rather than the total number of elements. As the number of lists increases, the memory consumed by the heap grows linearly with k. Therefore, the auxiliary space complexity simplifies to Big O of k.

Edge Cases

The input list of lists is completely empty or null
How to Handle:
Return a null pointer immediately since there are no linked lists to merge
The array contains lists that are all empty or null
How to Handle:
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
How to Handle:
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
How to Handle:
Value comparisons in the priority queue handle signed integers naturally based on their numeric magnitude
Multiple linked lists contain identical duplicate values
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Reuse existing node references from the input lists rather than instantiating new nodes to maintain O(1) auxiliary space
0/75 completed