AlgoMaster Logo

Kth Smallest Element in a Sorted Matrix

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force with Sorting

Intuition:

The simplest approach to solve this problem is by extracting all the elements from the matrix and placing them into a list. Once we have a list, we can sort it and then directly access the kth smallest element from this sorted list.

Algorithm:

  1. Create a list to store all elements of the matrix.
  2. Traverse the matrix and add each element to the list.
  3. Sort the list.
  4. Return the element at the kth index in the sorted list.

Code:

2. Min-Heap

Intuition:

To improve upon the brute force sorting solution, we can make use of a min-heap. The idea is to store each element in a min-heap so that we can extract the smallest element efficiently. Since the matrix rows (and columns) are sorted, we start placing elements into the heap one row at a time.

We maintain the heap for at most the size of the matrix's row by column, extract the smallest element from the heap k times, which will give us the kth smallest element.

Algorithm:

  1. Create a min-heap and add the first element of each row (along with row and column indices).
  2. Extract the smallest element from the heap k times.
  3. For each extraction, if the extracted element's column has another element in the row, add it to the heap.
  4. The kth extracted element is our answer.

Code:

Intuition:

The row and column sorted property of the matrix allows us to use binary search. We search within the range of the smallest and largest element of the matrix. For each midpoint value, count how many elements are less than or equal to it. Adjust the search range based on this count relative to k.

Algorithm:

  1. Initialize two pointers: left to the smallest element and right to the largest element in the matrix.
  2. Perform binary search:
    • Find the midpoint between left and right.
    • Count elements less than or equal to the midpoint.
    • If this count is less than k, move left up; otherwise, move right down.
  3. Once the search is complete, left contains the kth smallest element.

Code: