Understanding the Problem
We are given an N x N grid where:
- Each row is sorted in ascending order.
- Each column is also sorted in ascending order.
Our task is to find the (k)-th smallest element in this sorted matrix without using extra space.
Key Observations
1. The Matrix is Sorted Both Row-wise and Column-wise
- This means smaller values are concentrated at the top-left of the matrix, while larger values are at the bottom-right.
- We can exploit this sorted structure to efficiently find the (k)-th smallest element.
2. Binary Search on Values Instead of Indexes
- Since the smallest value is at
matrix[0][0]
and the largest value is atmatrix[N-1][N-1]
, our search space is ([matrix[0][0], matrix[N-1][N-1]]). - We use binary search on the possible values rather than searching directly for the (k)-th smallest element.
Approach
1. Binary Search on Value Range
- Step 1: Initialize left as
matrix[0][0]
(smallest value) and right asmatrix[N-1][N-1]
(largest value). - Step 2: Perform binary search:
- Compute mid = (left + right) / 2).
- Count the number of elements ≤ mid in the matrix.
- If the count is ≥ k, it means the (k)-th smallest value might be mid, so we move left.
- If the count is < k, it means the (k)-th smallest value must be larger, so we move right.
2. Counting Elements (≤ mid) Efficiently
To count the number of elements ≤ mid
in (O(N)) time:
- Start from the top-right corner (
matrix[0][N-1]
). - Move left while
matrix[r][c] > mid
. - Add the count of all elements in that column before moving down.
- Repeat for all rows.
Time Complexity of Counting: (O(N))
Complexity Analysis
- Binary search on values: O(log (max - min)), where
max
andmin
are the largest and smallest matrix values. - Counting elements ≤ mid: O(N) per iteration.
Total Complexity:
O(N log (max - min))