From 00f44a1c4776b3984679de407e33b1b8e9d429b2 Mon Sep 17 00:00:00 2001 From: Prad Nukala Date: Mon, 14 Sep 2026 12:50:08 -0400 Subject: [PATCH] =?UTF-8?q?docs(docs):=20add=20MDX=20page=20for=20Merge?= =?UTF-8?q?=E2=80=AFk=E2=80=AFSorted=E2=80=AFLists=20problem?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../(linked-list)/23-merge-k-sorted-lists.mdx | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 apps/docs/content/(linked-list)/23-merge-k-sorted-lists.mdx diff --git a/apps/docs/content/(linked-list)/23-merge-k-sorted-lists.mdx b/apps/docs/content/(linked-list)/23-merge-k-sorted-lists.mdx new file mode 100644 index 0000000..bb51333 --- /dev/null +++ b/apps/docs/content/(linked-list)/23-merge-k-sorted-lists.mdx @@ -0,0 +1,69 @@ +--- +title: '23. Merge k Sorted Lists' +description: You are given an array of k linked-lists lists, each linked-list is sorted in ascending order +sidebar: + label: 'Merge k Sorted Lists' + badge: 'Hard' +--- + +Heap / Priority Queue + +### 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 <= 10^4` +- `0 <= lists[i].length <= 500` +- `-10^4 <= lists[i][j] <= 10^4` +- `lists[i]` is sorted in ascending order. +- The sum of lists[i].length will not exceed 10^4. + +## Solution + +```py +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +import heapq + + +class Solution: + def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: + heap = [] + + # K log K + for i, node in enumerate(lists): + if node: + heapq.heappush(heap, (node.val, i, node)) + + D = ListNode() + cur = D + + # n log k + while heap: + val, i, node = heapq.heappop(heap) + cur.next = node + cur = node + node = node.next + + if node: + heapq.heappush(heap, (node.val, i, node)) + + # Time: O(N log k) + # Space: O(n) + return D.next +```