Leetcode #378: Kth Smallest Element in a Sorted Matrix
In this guide, we solve Leetcode #378 Kth Smallest Element in a Sorted Matrix in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Binary Search, Matrix, Sorting, Heap (Priority Queue)
Intuition
The problem structure suggests a monotonic decision, which makes binary search a natural fit.
By halving the search space each step, we reach the answer efficiently.
Approach
Search either directly on a sorted array or on the answer space using a check function.
Each check is fast, and the logarithmic search keeps the overall runtime low.
Steps:
- Define the search bounds.
- Check the mid point condition.
- Narrow the bounds until convergence.
Example
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
Python Solution
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
def check(matrix, mid, k, n):
count = 0
i, j = n - 1, 0
while i >= 0 and j < n:
if matrix[i][j] <= mid:
count += i + 1
j += 1
else:
i -= 1
return count >= k
n = len(matrix)
left, right = matrix[0][0], matrix[n - 1][n - 1]
while left < right:
mid = (left + right) >> 1
if check(matrix, mid, k, n):
right = mid
else:
left = mid + 1
return left
Complexity
The time complexity is O(log n) or O(n log n). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.