31. Kth Element in Matrix
โ GFG solution to the Kth Element in Matrix problem: find the kth smallest in a sorted matrix using binary search or heap. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given a n x n matrix in which each row and column is sorted in ascending order, find the kth smallest element in the matrix.
๐ Examples
Example 1
Input: n = 4, mat = [
[16, 28, 60, 64],
[22, 41, 63, 91],
[27, 50, 87, 93],
[36, 78, 87, 94]
], k = 3
Output: 27
Explanation: The 3rd smallest element in the sorted order is 27.Example 2
๐ Constraints
$1 \le n \le 500$
$1 \le \text{mat}[i][j] \le 10^4$
$1 \le k \le n^2$
โ
My Approach
We have three common approaches for finding the kth smallest element in a row- and column-sorted matrix:
1๏ธโฃ Binary Search on Value Range
Idea:
Let
low = mat[0][0],high = mat[n-1][n-1].Perform a binary search on the value range
[low, high]to find the smallestmidsuch that at leastkelements in the matrix are โคmid.
Counting โค mid:
For each row
i, maintain a pointerjstarting atn-1.While
j โฅ 0andmat[i][j] > mid, decrementj.Count of elements โค
midin rowiisj + 1.Sum up counts over all rows.
Binary Search Steps:
Compute
mid = low + (high - low) / 2.If
count(mid) < k, setlow = mid + 1.Else, set
high = mid.Continue until
low == high.
Result:
Return
low, which is the kth smallest element.
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n ร log(max - min)), where
maxandminare the matrix's largest and smallest values respectively.Expected Auxiliary Space Complexity: O(1), since we do not use extra memory except
๐งโ๐ป Code (C++)
๐งโ๐ป Code (Java)
๐ Code (Python)
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated