15% off all plans & roadmaps Use code

See plans

Kth Smallest Element in a Sorted Matrix

Updated

TL;DR: Find the kth smallest value in a matrix whose rows and columns are sorted. The winning idea is a min-heap that merges the rows one cell at a time, or a binary search on the value range that needs O(1) memory.

Problem

Given an n x n matrix where each row and column is sorted in ascending order, return the kth smallest element in the matrix.

The answer is the kth smallest element in sorted order, not the kth distinct element. Duplicates count separately.

You must find a solution with memory better than O(n^2).

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
  • -10^9 <= matrix[i][j] <= 10^9
  • All rows and columns of matrix are sorted in non-decreasing order.
  • 1 <= k <= n^2

Constraints that matter

  • n up to 300 means up to 90,000 cells. Copying and sorting all cells fits the time budget but breaks the memory rule.
  • Values range from -10^9 to 10^9. A binary search over that value range needs only about 31 halving steps.
  • Sorted rows and columns let you count the cells at most x with one staircase walk of about 2n steps. That count drives the binary search.
  • k up to n^2 means a heap loop can run almost 90,000 pops, so each pop has to cost only O(log n).

View on LeetCode

Hints

Hint 1

The matrix is not a flat list.

Hint 2

Ignore the sorted rows and columns.

Solution

Intuition

The matrix is not a flat list. Each row is a sorted list on its own, and the whole matrix is a set of sorted lists. Several sorted lists with a request for the kth item in the merged order is the signature of the K-way merge pattern.

Picture several sorted card piles, one per row. The heap is the top card of each pile in your hand, and each pop plays the smallest and draws the next card from its pile.

The second signal is that the answer is a value. Sorted rows and columns let you count how many cells are at most any value x. If that count is at least k, the answer is x or smaller. This turns the problem into a binary search on the answer.

Both ideas avoid building the full sorted list. The heap keeps one cursor per row and pops the smallest cursor k - 1 times. The search keeps a few numbers and never stores a cell.

Watch the pattern animation

Worked example

Input: matrix = [[1, 2, 3], [2, 3, 4], [3, 4, 5]], k = 1
Output: 1
Explanation: The matrix holds nine values. The smallest of them is the top-left cell, 1, so the 1st smallest value is 1. The dry runs below use this matrix and this k.

Approach 1: Brute force: flatten and sort

Ignore the sorted rows and columns. Copy every value into one list, sort the list, and read index k - 1. Sorting puts the kth smallest value at index k - 1 when indexing starts at zero. The method is correct, but it stores all n^2 values and does a full sort that the matrix structure already makes unnecessary.

Steps

  1. Create an empty list.
  2. Append every value from every row to the list.
  3. Sort the list in ascending order.
  4. Return the element at index k - 1.

Dry run

The matrix is [[1,2,3],[2,3,4],[3,4,5]] and k = 1.

Flattening row by row gives [1,2,3,2,3,4,3,4,5]. Sorting gives [1,2,2,3,3,3,4,4,5]. Index 0 holds 1, so the function returns 1.

Complexity

TimeO(n^2 log n)
SpaceO(n^2)

Let N = n^2 be the number of cells. Flattening visits each cell once, which costs O(N). A comparison sort on N values costs O(N log N), and log N = 2 log n, so the sort costs O(n^2 log n). The list holds N values, so the space is O(n^2), which breaks the memory rule.

PythonTested in our runner

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        # Flatten all n*n values into one list, then sort it
        flat = []
        for row in matrix:
            flat.extend(row)
        flat.sort()
        return flat[k - 1]

Approach 2: Binary search on value with a staircase count

What is slow: the brute force orders values it never needs to order, and it stores every cell. The insight is that the answer is a value between matrix[0][0] and matrix[n-1][n-1].

For any x, you can count the cells at most x in O(n) time. Start at the bottom-left corner and walk a staircase: when a cell is at most x, the column pointer moves right, and the count adds the pointer for each row. Binary search then finds the smallest x whose count reaches k.

Steps

  1. Set lo to matrix[0][0] and hi to matrix[n-1][n-1].
  2. While lo is less than hi, set mid to the midpoint of lo and hi.
  3. Count the cells at most mid. Start at row n-1 and column 0. For each row going up, move the column right while the cell is at most mid, then add the column pointer to the count.
  4. If the count is at least k, set hi to mid. Otherwise set lo to mid + 1.
  5. Return lo.

Dry run

The matrix is [[1,2,3],[2,3,4],[3,4,5]] and k = 1. Start with lo = 1 and hi = 5.

mid = 3. Row 2 [3,4,5] has 1 cell at most 3. Row 1 [2,3,4] has 2. Row 0 [1,2,3] has 3.

The count is 6, which is at least 1, so hi = 3.

mid = 2. Row 2 has 0, row 1 has 1, row 0 has 2. The count is 3, so hi = 2.

mid = 1. Row 2 has 0, row 1 has 0, row 0 has 1. The count is 1, so hi = 1.

Now lo = hi = 1, the loop stops, and the function returns 1.

Complexity

TimeO(n log C), where C = matrix[n-1][n-1] - matrix[0][0]
SpaceO(1)

The loop halves the value range each time, so it runs about log2(C) times. With values from -10^9 to 10^9, C is at most 2 * 10^9, so the loop runs about 31 times. Each count moves the row loop n times and the column pointer at most n times, so one count costs O(n). The search keeps only lo, hi, mid, count and the pointer, so the space is O(1).

PythonTested in our runner

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        n = len(matrix)
        lo, hi = matrix[0][0], matrix[n - 1][n - 1]
        while lo < hi:
            mid = (lo + hi) // 2  # floor division, so mid is always below hi
            # Count values <= mid with a staircase walk from the bottom-left
            count = 0
            c = 0
            for r in range(n - 1, -1, -1):
                while c < n and matrix[r][c] <= mid:
                    c += 1
                count += c
            if count >= k:
                hi = mid
            else:
                lo = mid + 1
        return lo

The K-way Merge infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

K-way Merge

Part of Heap (Priority Queue) Patterns

Approach 3: Min-heap K-way mergeOptimalK-way Merge

What is slow: the search spends its work on values that may not be in the matrix, and the brute force stores every cell. The insight is that each row is already sorted, so the kth smallest value is the kth value produced when you merge the rows.

A min-heap holds one entry per row: the current smallest unused cell in that row. Popping the heap returns the next smallest value overall. You then push the next cell from the same row, so each row keeps exactly one entry in the heap.

Why it is correct. The heap always holds the smallest unused cell of every row. Any unused cell in a row is at least as large as that row's entry, so the overall minimum must be one of the heap entries. Each pop removes the global minimum among unused cells, so after k - 1 pops the heap top is the kth smallest.

Steps

  1. Create a min-heap of (value, row, col) entries. Push matrix[r][0] for every row r.
  2. Repeat k - 1 times: pop the smallest entry (value, r, c).
  3. If c + 1 is less than n, push (matrix[r][c+1], r, c+1).
  4. Read the top of the heap. Its value is the kth smallest.

Dry run

The matrix is [[1,2,3],[2,3,4],[3,4,5]] and k = 1.

StepHeap contents (value, row, col)Pops doneOutput
Push first column(1,0,0), (2,1,0), (3,2,0)0none
Loop checkk - 1 = 0, so the loop body never runs0none
Read toptop is (1,0,0)01

The function returns 1. For k = 4 the loop would run three times and pop 1, 2 and 2. The top would then hold 3, which is the 4th smallest value.

Complexity

TimeO((n + k) log n), which is O(n^2 log n) in the worst case
SpaceO(n)

Let n be the matrix side. Pushing the n first-column cells costs O(n log n), since the heap never holds more than n entries.

The loop runs k - 1 times, and each run does one pop and at most one push on a heap of size at most n, so each run costs O(log n). The total is O(n log n + k log n) = O((n + k) log n).

The heap holds at most n entries, so the space is O(n).

PythonTested in our runner

import heapq

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        n = len(matrix)
        # One entry per row: (value, row, col), starting at column 0
        heap = [(matrix[r][0], r, 0) for r in range(n)]
        heapq.heapify(heap)
        for _ in range(k - 1):
            val, r, c = heapq.heappop(heap)
            # Replace the popped cell with the next cell in the same row
            if c + 1 < n:
                heapq.heappush(heap, (matrix[r][c + 1], r, c + 1))
        return heap[0][0]

Common mistakes

  • for r in range(n): for c in range(n): heappush(...) pushes all n^2 cells. Seed the heap with column 0 only, then push the next cell in a row when you pop from that row.
  • Missing the c + 1 < n guard before reading matrix[r][c + 1]. Past the end of a row the read is out of range or lands in the wrong row. Check the column bound before the push.
  • Reading the popped element on the kth iteration instead of the heap top. The heap loop runs k - 1 times, so the answer is the top after the loop, not the last value popped inside it.
  • Writing mid = (lo + hi) / 2 in C++ or Java with negative values. Integer division truncates toward zero, so mid can equal hi and the loop stops moving. Use lo + (hi - lo) / 2 with a long type, or floor division.
  • Using count > k in the binary search. The search needs the smallest value with at least k cells at or below it, so the test is count >= k.
  • Walking the staircase from the top-left corner. Start at the bottom-left, and move the column pointer right as the row index goes up. Starting at the wrong corner counts the wrong cells.

Edge cases

  • n = 1, matrix [[-5]], k = 1: returns -5. The binary search loop never runs because lo equals hi, and the heap loop runs zero times.
  • k = 1: the answer is matrix[0][0], the smallest cell. The heap does no pops and the binary search converges to that value.
  • k = n^2: the answer is matrix[n-1][n-1], the largest cell. The heap does n^2 - 1 pops, which is the worst case for the loop.
  • All values equal, matrix [[2,2],[2,2]] with k = 3: returns 2. Repeated values count separately, so the count includes every copy.
  • Mixed signs, matrix [[-10,-1],[0,4]] with k = 2: the sorted order is -10, -1, 0, 4, so the answer is -1.
  • Duplicates across rows, matrix [[1,3],[3,5]] with k = 3: the sorted order is 1, 3, 3, 5, so the answer is 3.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Kth Smallest Element in a Sorted Matrix, with how to answer them.

Unlock the follow-ups

Kth Smallest Element in a Sorted Matrix FAQ

What is the time complexity of Kth Smallest Element in a Sorted Matrix?

The min-heap approach runs in O((n + k) log n), which is O(n^2 log n) in the worst case when k is near n^2. Binary search on value runs in O(n log C), where C is the value range. The brute force sort runs in O(n^2 log n) and uses O(n^2) space.

Why use a min-heap for Kth Smallest Element in a Sorted Matrix?

Each row is sorted, so the smallest unused cell is always the front of some row. A min-heap with one entry per row finds that smallest cell in O(log n) time. Popping in order k - 1 times leaves the kth value at the top.

Can Kth Smallest Element in a Sorted Matrix be solved in O(1) extra space?

Yes. Binary search on the value range keeps only a few numbers and needs no heap or list. The heap approach needs O(n) space, and the brute force needs O(n^2).

Does Kth Smallest Element in a Sorted Matrix ask for the kth distinct value?

No. Duplicates count separately, so in the matrix [[1,1],[1,1]] with k = 3 the answer is 1. Removing duplicates before counting gives the wrong answer.

What is the C++ or Java gotcha for the heap version?

C++ priority_queue is a max-heap by default, so you must pass greater for a min-heap. Java PriorityQueue is a min-heap, but the comparator must compare the first array element, not the whole array.

Asked at

See which companies ask this — Pro

Practise it