Matrix Median
Matrix Median is a GFG problem (Medium). Its practice page calls it Median in a Row-Wise Sorted Matrix. Each row of mat is sorted, and the number of rows n and columns m are both odd. Return the median: the middle value if all n · m numbers were sorted into one list.
- Rows are sorted, but columns and the matrix as a whole are not.
- Values run from 1 to 2,000, so a search over values takes only about 11 rounds.
Flattening and sorting works, but it costs O(n·m log(n·m)) time and O(n·m) memory and ignores the sorted rows.
- 1 <= n, m <= 400
- n and m are both odd
- 1 <= mat[i][j] <= 2000
- Each row is sorted in non-decreasing order
Intuition
Searching for the median's position does not work, because the matrix is not sorted as a whole. Search for its value instead.
For any number x, count how many entries are at most x. Each sorted row answers that with one binary search, and the count never drops as x grows. Since n · m is odd, exactly half = n·m // 2 entries come before the median in sorted order. So the median is the smallest value whose count is more than half, and a binary search over the value range finds it.
"Find the k-th smallest value, but the data is only sorted in pieces" is a binary search on the answer: guess a value, count how many entries are at most that value, and move the guess. Kth Smallest Element in a Sorted Matrix uses the same idea.
Approach
Before reading on, pick a number x and work out how fast you can count the entries at most x using only the sorted rows. Then decide what that count must be when x is the median. Aim for better than O(n·m).
Set the value range
Start lo at the smallest first element of any row and hi at the largest last element. Because every row is sorted, its smallest entry is in the first column and its largest in the last, so the median lies between lo and hi.
Count the entries at most mid
Take mid = (lo + hi) // 2 and add bisect_right(row, mid) over all rows. In a sorted row, the insert position just right of mid equals the number of entries that are <= mid, found in O(log m).
Move the range
If count <= half, too few entries are at most mid, so the median is larger: set lo = mid + 1. Otherwise more than half the entries are at most mid, so mid may be the median itself: set hi = mid and keep it in range.
Why the answer is a real entry
The loop ends with lo == hi, the smallest value whose count passes half. The count only changes at values that appear in the matrix, so that smallest value must be an entry, even though many mid values tried on the way were not.
Code in Python, C++ and Java
Common pitfalls
Counting entries strictly below mid
count += bisect_left(row, mid)
count += bisect_right(row, mid)
bisect_left counts entries < mid, so a value is not counted when mid equals it. On [[1,3,5],[2,6,9],[3,6,9]] the search then skips past 5 and returns 6. The median is the first value where entries <= x pass half, so equal entries must be counted.
Dropping mid when the count is large enough
else:
hi = mid - 1else:
hi = midA count above half means mid itself may be the median, so it has to stay in the range. With mid - 1, the same first example returns 4 instead of 5, a value that is not even in the matrix.
Edge cases
For [[3], [4], [8]] each row has one entry, so each row count is 0 or 1 and the search returns 4 like any other matrix.
lo and hi start equal, so the loop never runs and that value is returned.
Complexity
lo and hi reads two entries per row.Matrix Median FAQ
Why not merge the rows with a min-heap?
A heap holding the head of each row can pop entries in sorted order, and the (half + 1)-th pop is the median. That takes O(n·m log n) time because about half of all entries are popped. The value search touches only a handful of entries per row in each of its 11 or so rounds.
What if the number of entries were even?
The median would be the average of the two middle values. The same search finds the k-th smallest value for any k: it is the smallest x whose count of entries at most x is at least k. Run it for k = n·m / 2 and k = n·m / 2 + 1, then average.
LeetCode 2387 looks the same. Is it?
Yes. Median of a Row Wise Sorted Matrix (LeetCode 2387, premium) asks the same question with a larger value range. The value search only gains a few extra rounds, so the same code works.