> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Merge k Sorted Lists Python Solution

> Tested Python solution for LeetCode 23 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 23, Hard. Topics: Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort. [View on LeetCode](https://leetcode.com/problems/merge-k-sorted-lists/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 23   # by problem number
lcpy gen -s merge_k_sorted_lists   # by problem name
```

## Problem

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

### Examples

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

```
Input: lists = []
Output: []
```

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

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/merge_k_sorted_lists/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/merge_k_sorted_lists/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import ListNode


class Solution:
    # Time: O(n log k) where n is total nodes, k is number of lists
    # Space: O(log k) for recursion stack
    def merge_k_lists(self, lists: list[ListNode[int] | None]) -> ListNode[int] | None:
        if not lists:
            return None
        return self._divide_conquer(lists, 0, len(lists) - 1)

    def _divide_conquer(
        self, lists: list[ListNode[int] | None], left: int, right: int
    ) -> ListNode[int] | None:
        if left == right:
            return lists[left]

        mid = (left + right) // 2
        l1 = self._divide_conquer(lists, left, mid)
        l2 = self._divide_conquer(lists, mid + 1, right)
        return self._merge_two(l1, l2)

    def _merge_two(
        self, l1: ListNode[int] | None, l2: ListNode[int] | None
    ) -> ListNode[int] | None:
        dummy = ListNode(0)
        curr = dummy

        while l1 and l2:
            if l1.val <= l2.val:
                curr.next = l1
                l1 = l1.next
            else:
                curr.next = l2
                l2 = l2.next
            curr = curr.next

        curr.next = l1 or l2
        return dummy.next
```

## Complexity

| Time                                                    | Space                        |
| ------------------------------------------------------- | ---------------------------- |
| O(n log k) where n is total nodes, k is number of lists | O(log k) for recursion stack |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
