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

# Kth Smallest Element in a Sorted Matrix

> Tested Python solution for LeetCode 378 with 33 pytest cases. Generate a practice environment with lcpy.

LeetCode 378, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Binary Search](/catalog/topics/binary-search), [Sorting](/catalog/topics/sorting), [Heap (Priority Queue)](/catalog/topics/heap-priority-queue), [Matrix](/catalog/topics/matrix). [View on LeetCode](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/).

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

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

## Problem

Given an `n x n` matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

You must find a solution with a memory complexity better than O(n2).

### Examples

```
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
```

```
Input: matrix = [[-5]], k = 1
Output: -5
```

### Constraints

* n == matrix.length == matrix\[i].length
* 1 \<= n \<= 300
* -10^9 \<= matrix\[i]\[j] \<= 10^9
* All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
* 1 \<= k \<= n2

**Follow up:**

* Could you solve the problem with a constant memory (i.e., O(1) memory complexity)?
* Could you solve the problem in O(n) time complexity?

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n * log(max - min))
    # Space: O(1)
    def kth_smallest(self, matrix: list[list[int]], k: int) -> int:
        def count_at_most(target: int) -> int:
            count = 0
            row, col = len(matrix) - 1, 0
            while row >= 0 and col < len(matrix):
                if matrix[row][col] <= target:
                    count += row + 1
                    col += 1
                else:
                    row -= 1
            return count

        lo, hi = matrix[0][0], matrix[-1][-1]
        while lo < hi:
            mid = lo + (hi - lo) // 2
            if count_at_most(mid) < k:
                lo = mid + 1
            else:
                hi = mid
        return lo
```

## Complexity

| Time | Space |
| - | - |
| O(n \* log(max - min)) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.