Introduction
This problem asks us to find the kth smallest element in an n × n matrix where:
Each row is sorted in ascending order.
Each column is sorted in ascending order.
The challenge is to find the kth smallest element efficiently without flattening and sorting the entire matrix.
Key Idea
We do not flatten the matrix into a one-dimensional array and sort it, as that would be inefficient for large matrices.
Instead, we use a powerful technique known as:
Binary Search on Answer
Why Binary Search Works
Because the matrix is sorted both row-wise and column-wise:
Small values are located near the top-left corner.
Large values are located near the bottom-right corner.
This ordering allows us to binary search over the range of possible values instead of searching through positions.
The Strategy
For a guessed value mid, count:
How many elements are ≤ mid?
Based on that count:
If
count ≥ k, the answer may bemidor a smaller value, so move left.If
count < k, the answer must be larger, so move right.
Counting Elements Efficiently
A key part of the solution is counting how many elements are less than or equal to mid.
Instead of scanning the entire matrix, we can do it in O(n) time.
Traversal Strategy
Start from the top-right corner.
For each position:
Case 1: Current Element ≤ Mid
If:
mat[row][col] ≤ mid
Then:
Every element from column
0tocolin the same row is also≤ mid.Add
(col + 1)to the count.Move down to the next row.
Case 2: Current Element > Mid
If:
mat[row][col] > mid
Then:
The current element and all elements below it in that column are too large.
Move left.
This allows counting in linear time relative to the matrix size.
Algorithm
Step 1: Define the Search Range
The smallest possible answer is:
mat[0][0]
The largest possible answer is:
mat[n - 1][n - 1]
Initialize:
low = mat[0][0]
high = mat[n - 1][n - 1]
Step 2: Perform Binary Search
While:
low < high
Compute:
mid = low + (high - low) / 2
Count the number of elements less than or equal to mid.
Decision
If:
count < k
Move right:
low = mid + 1
Otherwise:
high = mid
Step 3: Return the Answer
When the search ends:
low == high
This value represents the smallest number for which at least k elements are less than or equal to it.
Return:
low

Join the conversation! Your thoughts help the community grow.