Skip to main content

Kth Smallest Element in a Sorted Matrix - Solution & Explanation

MediumArrayBinary SearchSortingHeap (Priority Queue)17 min readAsked at: Amazon, Microsoft, Apple +7
Practice this problem

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.

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

 

Example 1:

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

Example 2:

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

 

Constraints:

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 300
  • -109 <= matrix[i][j] <= 109
  • 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? The solution may be too advanced for an interview but you may find reading this paper fun.

Approach Overview

Problem Overview: You are given an n x n matrix where each row and column is sorted in ascending order. The task is to return the kth smallest element in the matrix. Because both rows and columns are sorted, the matrix behaves like multiple sorted lists merged together.

Approach 1: Flatten + Sort (O(n² log n²) time, O(n²) space)

The most direct solution ignores the sorted structure. Iterate through the matrix, push every element into a list, and sort it. After sorting, the element at index k - 1 is the answer. This approach is simple but inefficient because it processes all n² elements even though the matrix already provides ordering guarantees. It’s mainly useful as a baseline or quick prototype using basic array and sorting operations.

Approach 2: Min-Heap (O(k log n) time, O(n) space)

This method treats each row like a sorted list and merges them using a min-heap. Push the first element of every row into the heap along with its row and column index. Repeatedly extract the smallest element from the heap. When an element (r, c) is removed, push the next element in that row (r, c+1) if it exists. After performing k heap extractions, the last popped value is the answer. The heap size never exceeds n, making operations efficient. This technique is a classic application of heap (priority queue) for merging sorted structures.

Approach 3: Binary Search on Value Range (O(n log(max-min)) time, O(1) space)

The optimal solution performs binary search over the value range rather than indices. The smallest possible value is matrix[0][0] and the largest is matrix[n-1][n-1]. For a chosen midpoint, count how many numbers in the matrix are less than or equal to it. Because rows and columns are sorted, this count can be computed in O(n) by starting from the bottom-left corner and moving either up or right. If the count is less than k, move the search range higher; otherwise move it lower. The search converges to the kth smallest value without explicitly storing elements.

Recommended for interviews: The binary search solution is usually what interviewers expect because it leverages the sorted matrix structure and achieves O(n log(max-min)) time with constant extra space. The heap approach is also widely accepted and easier to implement. Mentioning the flatten-and-sort baseline shows understanding of the problem before optimizing.

Approach 1: Use Min-Heap

By using a min-heap (priority queue), you can efficiently extract the smallest elements one by one. Initially, insert the first element of each row into the heap. Then, repeat the process of extracting the smallest element and inserting the next element from the corresponding row. Continue this until you extract the k-th smallest element.

In this C solution, we maintain a min-heap (priority queue) of the smallest elements from each row of the matrix. Initially, we insert the first element of each row into the heap. We then extract the smallest element from the heap and insert the next element from the same row into the heap. We repeat this process until we find the k-th smallest element.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(k log n), where n is the size of each row/column.
Space Complexity: O(n), due to the maintained heap.

Try this approach in the editor →

Approach 2: Use Binary Search

This approach uses binary search over the range of possible values in the matrix to find the k-th smallest element. The idea is to repeatedly narrow the range by counting the number of elements in the matrix that are less than or equal to the current middle value. Depending on this count, adjust the binary search range to hone in on the k-th smallest element.

This C solution employs binary search on the matrix's values. By calculating the number of elements less than or equal to the mid-point value in the range, the solution dynamically adjusts search bounds until the k-th smallest is uncovered at the low-end track of the narrowed range. The logic banks on ordered nature without direct sorting.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log(max-min)), resulting from binary search log sweeps invoking count linear phase.
Space Complexity: O(1), since alterations occur in-place within computation limits of primitive variables.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Use Min-Heap

Time Complexity: O(k log n), where n is the size of each row/column.
Space Complexity: O(n), due to the maintained heap.

Use Binary Search

Time Complexity: O(n log(max-min)), resulting from binary search log sweeps invoking count linear phase.
Space Complexity: O(1), since alterations occur in-place within computation limits of primitive variables.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Flatten Matrix + SortO(n² log n²)O(n²)Simple baseline when constraints are small or quick implementation is needed
Min-Heap (Merge Sorted Rows)O(k log n)O(n)Good when k is small relative to n² and you want a straightforward heap solution
Binary Search on Value RangeO(n log(max-min))O(1)Best for interviews and large matrices since it uses the sorted row/column property efficiently

Video Solution

Kth Smallest element in a matrix | Leetcode #378 • Techdose • 25,225 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Kth Smallest Element in a Sorted Matrix easy or hard?
The problem is usually classified as Medium difficulty. A straightforward heap implementation is manageable once you recognize the matrix behaves like multiple sorted lists. The binary search optimization requires deeper insight into searching the value space and leveraging row and column ordering.
Kth Smallest Element in a Sorted Matrix Python or Java solution?
Python and Java solutions typically implement either a PriorityQueue/min-heap or binary search. The heap version pushes the first element of each row and repeatedly pops the smallest until k elements are removed. The binary search version checks how many values are <= mid using a linear scan from the bottom-left corner.
What is the best approach for Kth Smallest Element in a Sorted Matrix?
Binary search on the value range is generally considered the best approach. It searches between the smallest and largest matrix values and counts how many elements are <= mid using the sorted row and column property. This runs in O(n log(max-min)) time and O(1) extra space. A min-heap approach with O(k log n) time is also commonly accepted in interviews.
How to solve Kth Smallest Element in a Sorted Matrix in O(n log range)?
Perform binary search between matrix[0][0] and matrix[n-1][n-1]. For each midpoint, count how many elements in the matrix are less than or equal to it by scanning from the bottom-left corner and moving up or right. If the count is smaller than k, shift the search range higher; otherwise move it lower. The final boundary value becomes the kth smallest element.
Is Kth Smallest Element in a Sorted Matrix asked at Google/Amazon/Meta?
Kth Smallest Element in a Sorted Matrix is a common interview problem at large tech companies including Google, Amazon, and Meta. It tests understanding of binary search on answer space, heap usage, and exploiting sorted matrix properties. Variants of the problem appear in coding interviews and competitive programming.
What data structure is used in Kth Smallest Element in a Sorted Matrix?
Two main techniques appear in solutions. A min-heap (priority queue) is used to merge sorted rows similarly to merging k sorted lists. The optimal solution relies on binary search over the value range combined with matrix traversal, which avoids storing extra elements.
What is the time complexity of Kth Smallest Element in a Sorted Matrix?
The optimal binary search solution runs in O(n log(max-min)) time where n is the matrix dimension and max-min is the numeric range of values. Each binary search step counts elements <= mid in O(n) time. The heap-based method runs in O(k log n) time with O(n) space.

Ready to solve this problem?

Practice Kth Smallest Element in a Sorted Matrix with our built-in code editor and test cases.

Practice on FleetCode