Kth Smallest Element in a Sorted Matrix

Kth Smallest Element in a Sorted Matrix is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Heap (Priority Queue) Patterns pattern, in the K-way Merge subpattern.

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.

Topics and companies

Topics: Array, Binary Search, Sorting, Heap (Priority Queue), Matrix.

Reported in interviews at Facebook, Google, Amazon.

How to practise Kth Smallest Element in a Sorted Matrix on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(k * log(min(n, m, k))), with n x m matrix time and O(min(n, m, k)) space.

Open Kth Smallest Element in a Sorted Matrix in the code editor, or read the Kth Smallest Element in a Sorted Matrix editorial for a worked solution with its approach and complexity analysis.

Where Kth Smallest Element in a Sorted Matrix sits in the DSA pattern sheet

Problems related to Kth Smallest Element in a Sorted Matrix

Other problems that use the same K-way Merge and Heap (Priority Queue) Patterns techniques:

Preparing this workspace.