⚡Flashcard Drill➔
NeetCode #341LC-23HardLinked ListBlind 75NC 150NC 250
← Back to All Problems

#341 · #23 · Merge k Sorted Lists(合并 K 个升序链表)

📌 Problem Statement & Constraints

You are given an array of k sorted linked lists. Merge them into one sorted list and return its head. Constraints: k is in [0, 10^4], the total number of nodes is at most 10^4.

💡 Core Algorithmic Approaches

  1. Put the head of each non-empty list into a min-heap keyed by value.
  2. Repeatedly pop the smallest node, append it to the result, and push its successor.
  3. Important: heap entries must be comparable, and ListNode objects are not, so include a tie-breaker such as the list index in the tuple.
  4. This is O(N log k) where N is the total number of nodes, versus O(N log N) for the concatenate-and-sort approach.

💻 Benchmark Python3 Implementation

class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        import heapq
        h = []
        for i, node in enumerate(lists):
            if node:
                # include the index i so tuples never compare ListNode objects
                heapq.heappush(h, (node.val, i, node))
        dummy = tail = ListNode(0)
        while h:
            val, i, node = heapq.heappop(h)
            tail.next = node
            tail = node
            if node.next:
                heapq.heappush(h, (node.next.val, i, node.next))
        return dummy.next

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(N log k): each of the N nodes is pushed and popped once.
💾 Space Complexity
O(k) for the heap.

⚠️ Interview Pitfalls & Follow-ups

  • Pushing bare ListNode objects: when two values are equal, Python would try to compare the nodes and raise TypeError. Always include a unique tie-breaker.
  • Concatenating all lists and sorting: O(N log N) and requires O(N) extra space.
  • Merging lists pairwise in a loop: correct and O(N log k) if done as a divide-and-conquer, but O(N * k) if done naively.
  • Skipping empty lists: pushing None would break the heap; the if node guard is required.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Linked List Problems

中文速览与面试要点

合并 K 个升序链表

给你一个链表数组,每个链表都已经按升序排列。请你将所有链表合并到一个升序链表中,返回合并后的链表。约束:k == lists.length;0 ≤ k ≤ 10^4;0 ≤ lists[i].length ≤ 500;-10^4 ≤ lists[i][j] ≤ 10^4;lists[i] 按升序排列;lists[i].length 的总和不超过 10^4。

核心要点

  • 方案一 · 逐一合并 :把第 1 个链表依次与第 2、3…个合并。若每次合并结果不断变长,最坏为 O(k²n)。
  • 方案二 · 分治两两合并(推荐) :每轮把链表两两配对合并,共 log k 轮,每轮处理 O(N) 个节点,总 O(N log k)。
  • 方案三 · 最小堆(多路归并) :把每个链表的头节点入堆,每次弹出最小者接到结果上,并把它的后继入堆。时间 O(N log k)、空间 O(k)。
  • 为什么分治优于逐一 :逐一合并时,早期合并产生的大链表会被反复遍历 k 次;分治让每个节点只参与 log k 轮合并。

常见陷阱

  • 逐一顺序合并 :虽然能过,但最坏 O(k²n)。面试中应给出分治或堆解法。
  • 堆中存 (val, node) 元组 :当两个节点的 val 相同时,Python 会尝试比较 node 对象,而 ListNode 未定义 < ,会抛 TypeError。必须加入下标 i 作为第二关键字(本解用 (val, i, node) )。
  • 分治法中 lists[i+1] 越界 :链表数为奇数时最后一个元素没有配对,需要 if i + 1 < len(lists) 判断。
  • 分治法中忘记处理空列表 : lists 可能为空或只含 None,需在 _merge_two 中正确处理。

参考实现

import heapq

class Solution:
    def mergeKLists(self, 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(self._merge_two(l1, l2))
            lists = merged
        return lists[0]

    def _merge_two(self, a, b):
        dummy = ListNode()
        tail = dummy
        while a and b:
            if a.val <= b.val:
                tail.next = a
                a = a.next
            else:
                tail.next = b
                b = b.next
            tail = tail.next
        tail.next = a or b
        return dummy.next

# 方案二:最小堆(多路归并)
# class Solution:
#     def mergeKLists(self, lists):
#         heap = []
#         for i, node in enumerate(lists):
#             if node:
#                 heapq.heappush(heap, (node.val, i, node))
#         dummy = ListNode()
#         tail = dummy
#         while heap:
#             val, i, node = heapq.heappop(heap)
#             tail.next = node
#             tail = node
#             if node.next:
#                 heapq.heappush(heap, (node.next.val, i, node.next))
#         return dummy.next