Median of a Row Wise Sorted Matrix
Pattern: Binary search on 2D matrices
Binary search on the value. For a guess x, count the cells at most x with an upper bound in each row. The median is the smallest x with more than half of the cells at most x.
The problem
You are given a matrix with an odd number of cells, where each row is sorted. Return the median of all its values, the
middle value when they are sorted, in less than O(R × C) time. For example, [[1, 1, 2], [2, 3, 3], [1, 3, 4]] gives 2,
and [[1, 1, 3, 3, 4]] gives 3.
The function name matrixMedian matches LeetCode, where this problem needs a premium account. Use the link above for
the exact statement and limits.
Think first
- For the median
m, how many cells are at mostm? How many are at mostm - 1? - For any guess
x, how quickly can you count the cells at mostxin one sorted row? - Does that count grow when
xgrows?
Hints
Brute force, and why it fails
Copy every value into one list and sort it: O(R × C × log(R × C)) time and O(R × C) memory. Binary search on the value costs O(R log C) per guess and about 32 guesses.
The key insight
You cannot sort the matrix cheaply, but you can count the cells below any value cheaply. A count that grows with the value turns "find the middle" into a binary search on values.
Dry run
| lo | 1 |
|---|---|
| hi | 4 |
| need | 5 |
grid has rows 1 1 2, 2 3 3 and 1 3 4, 9 cells in all. The median needs at least 9 / 2 + 1 = 5 cells at most it. Values run from 1 to 4.
The plan
lo = min of first column, hi = max of last column
need = R * C / 2 + 1
while lo < hi:
mid = lo + (hi - lo) / 2
if sum over rows of upperBound(row, mid) >= need: hi = mid
else: lo = mid + 1
return lo
Complexity
- Time
O(R log C log V)- Space
O(1)
V is the range of values. Each of about log₂ V guesses does one binary search per row.
Edge cases
- One cell: that value.
- All values equal: that value.
- Negative values: the range starts below 0, and
lo + (hi - lo) / 2still rounds the right way.
I've built my logic, show the code
Java
class Solution {
public int matrixMedian(int[][] grid) {
int lo = Integer.MAX_VALUE, hi = Integer.MIN_VALUE;
for (int[] r : grid) { lo = Math.min(lo, r[0]); hi = Math.max(hi, r[r.length - 1]); }
int need = grid.length * grid[0].length / 2 + 1; // the median has at least this many values <= it
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (countAtMost(grid, mid) >= need) hi = mid; // mid is the median or above it
else lo = mid + 1;
}
return lo;
}
private int countAtMost(int[][] grid, int x) {
int count = 0;
for (int[] r : grid) { // upper bound of x in each sorted row
int lo = 0, hi = r.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (r[mid] > x) hi = mid;
else lo = mid + 1;
}
count += lo;
}
return count;
}
}C++
class Solution {
public:
int matrixMedian(vector<vector<int>>& grid) {
int lo = INT_MAX, hi = INT_MIN;
for (const vector<int>& r : grid) { lo = min(lo, r[0]); hi = max(hi, r.back()); }
int need = static_cast<int>(grid.size() * grid[0].size() / 2) + 1; // values <= the median
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (countAtMost(grid, mid) >= need) hi = mid; // mid is the median or above it
else lo = mid + 1;
}
return lo;
}
int countAtMost(vector<vector<int>>& grid, int x) {
int count = 0;
for (vector<int>& r : grid) count += static_cast<int>(upper_bound(r.begin(), r.end(), x) - r.begin());
return count;
}
};Python
class Solution:
def matrixMedian(self, grid: list[list[int]]) -> int:
lo, hi = min(r[0] for r in grid), max(r[-1] for r in grid)
need = len(grid) * len(grid[0]) // 2 + 1 # the median has at least this many values <= it
while lo < hi:
mid = (lo + hi) // 2
if self.count_at_most(grid, mid) >= need:
hi = mid # mid is the median or above it
else:
lo = mid + 1
return lo
def count_at_most(self, grid: list[list[int]], x: int) -> int:
count = 0
for r in grid: # upper bound of x in each sorted row
lo, hi = 0, len(r)
while lo < hi:
mid = (lo + hi) // 2
if r[mid] > x:
hi = mid
else:
lo = mid + 1
count += lo
return countCommon mistakes
- Searching for exactly
T / 2cells, which is off by one. - Using the lower bound in each row, which counts cells smaller than
xinstead of at mostx. - Writing
(lo + hi) / 2with negative numbers in Java or C++, which rounds towards zero and can loop forever.