Median of a row-wise sorted matrix, without sorting it
The median of a row-wise sorted matrix is found by binary searching over values, not positions: for a candidate value x, count how many entries are at most x using a binary search in each row, and find the smallest x whose count passes half the total. With R rows and C columns that takes O(R log C log M) time, where M is the value range, and O(1) extra space.
By Evin JohnPublished 8 min read
Problem statement, rephrased
You have a grid of integers with R rows and C columns. Each row is sorted from small to large, but the columns are not sorted, and one row's last value may be bigger than the next row's first. The total number of entries is odd. Return the median: the value that would sit exactly in the middle if every entry were written out in sorted order.
| Grid (rows) | All values sorted | Median |
|---|---|---|
| [2, 6, 9], [1, 4, 10], [3, 5, 7] | 1 2 3 4 5 6 7 9 10 | 5 |
| [4], [1], [8] | 1 4 8 | 4 |
| [1, 1, 3, 3, 3] | 1 1 3 3 3 | 3 |
| [-5, 0, 12] | -5 0 12 | 0 |
Ask early about the even case. With an even count there are two middle values, and you need to know whether to return the lower one, the upper one, or their average. Most versions of this problem rule it out by promising an odd count; the code below assumes that.
The direct way: flatten and sort
Copy every entry into one list, sort it, and read the element at index RC / 2 (rounded down). It is correct and takes one line, but it ignores the fact that each row is already sorted, and it needs memory for all RC entries.
def matrix_median_sorted(grid):
flat = sorted(v for row in grid for v in row)
return flat[len(flat) // 2]A middle ground merges the rows with a min-heap of size R and pops (RC + 1) / 2 times. That uses the row order and only O(R) memory, but it still does about RC / 2 heap operations, so it is O(RC log R). Mention it, then move on.
Searching the value range
Turn the question around. Instead of asking which value sits in the middle, ask: for a given number x, how many entries are less than or equal to x? Call that count(x). Because each row is sorted, count(x) for one row is a single upper-bound binary search, so the whole count takes O(R log C).
count(x) never decreases as x grows. The median is the smallest x for which count(x) reaches need, where need is RC / 2 rounded down, plus one. So binary search on x between the smallest first-column value and the largest last-column value. If count(mid) is below need, the median is bigger than mid; otherwise mid might be the median or something smaller works too.
Why is the result always an actual entry and not some value in a gap? count only jumps when x reaches a value that exists in the grid. If x were not an entry, then x minus one would have the same count, so x would not be the smallest qualifying value.
from bisect import bisect_right
def matrix_median(grid):
rows, cols = len(grid), len(grid[0])
need = rows * cols // 2 + 1
low = min(row[0] for row in grid)
high = max(row[-1] for row in grid)
while low < high:
mid = (low + high) // 2
count = sum(bisect_right(row, mid) for row in grid)
if count < need:
low = mid + 1
else:
high = mid
return lowfunction countAtMost(row, x) {
let lo = 0;
let hi = row.length;
while (lo < hi) {
const m = (lo + hi) >> 1;
if (row[m] <= x) lo = m + 1;
else hi = m;
}
return lo;
}
function matrixMedian(grid) {
const need = Math.floor((grid.length * grid[0].length) / 2) + 1;
let low = Infinity;
let high = -Infinity;
for (const row of grid) {
low = Math.min(low, row[0]);
high = Math.max(high, row[row.length - 1]);
}
while (low < high) {
const mid = Math.floor((low + high) / 2);
let count = 0;
for (const row of grid) count += countAtMost(row, mid);
if (count < need) low = mid + 1;
else high = mid;
}
return low;
}Two details in the JavaScript are easy to get wrong. Math.floor rather than a bit shift for the value midpoint matters because >> first converts to a 32-bit integer, which breaks on very large values; for array indexes the shift is fine. And countAtMost must return the position after the last value that is at most x, which is why the comparison is <=.
Trace on the 3 by 3 grid
Take the first grid from the table. There are nine entries, so need is 5. The range starts at low 1 and high 10. Guess 5: the rows hold 1, 2 and 2 values that are at most 5, which sums to 5, enough, so high becomes 5. Guess 3: the counts are 1, 1 and 1, total 3, too few, so low becomes 4. Guess 4: counts 1, 2 and 1, total 4, still short, so low becomes 5. Now low equals high and the median is 5.
Complexity side by side
| Approach | Time | Extra memory |
|---|---|---|
| Flatten and sort | O(RC log RC) | O(RC) |
| Merge rows with a heap, stop halfway | O(RC log R) | O(R) |
| Binary search on value with row counts | O(R log C log M) | O(1) |
The log M factor is about 32 steps for values that fit in 32 bits, so in practice the value search behaves like O(R log C) times a small constant. When values are huge and rows are few, this is a large win over sorting everything.
Edge cases
- A single row: the answer is the row's middle element, and the search still finds it.
- A single column: rows have one value each, so every count is a 0 or 1 comparison.
- Many repeated values, such as [1, 1, 3, 3, 3]:
bisect_rightcounts all copies, which is what makes duplicates work. - Negative numbers: the midpoint must round down, not toward zero, or the loop can stall. Python's
//andMath.floorboth round down. - An even number of entries, if the interviewer relaxes the rule: run the search twice for the two middle ranks and combine them as agreed.
Common mistakes
- Searching over indexes instead of values. The grid is not globally sorted, so there is no single index range to bisect.
- Using a lower bound in the count. Counting values strictly below x shifts every count and returns the wrong neighbor when duplicates sit at the median.
- Setting `need` to RC / 2 instead of RC / 2 + 1. With nine entries the median is the fifth smallest, not the fourth.
- Taking low and high from the first and last row only. Rows are not ordered against each other, so the smallest value can be in any row's first column.
- Truncating toward zero for the midpoint. In C++ or Java,
(low + high) / 2truncates toward zero, which misbehaves with negative ranges. Use a floor orlow + (high - low) / 2.
Explaining the trick in an interview
Fictional example
- Candidate
- Sorting everything works but throws away the row order. Instead I will ask, for a value x, how many entries are at most x. Each row answers that with a binary search.
- Candidate
- That count grows with x, so I can binary search on x itself between the smallest and largest entries. The median is the first x whose count reaches half the entries plus one.
- Interviewer
- Could the answer be a value that is not in the grid?
- Candidate
- No. The count only changes at values that exist, so the smallest x that qualifies has to be one of them.
Where to go next
Kth Smallest Number in Multiplication Table uses the same count-then-search idea on a table you never build. Find Minimum in Rotated Sorted Array II is a good contrast, because there the search runs over positions. Magnetic Force Between Two Balls searches an answer range with a greedy test instead of a count. Matrix basics are covered in the data structure interview questions.
Natively during practice
If you practice matrix problems from screenshots, Natively can read the grid and the question from the image and suggest an approach to compare with your own once you have tried. It can also keep a transcript of a mock interview on your computer, which helps you check whether you justified why the answer must be an actual entry. Details are on the AI interview assistant page.
Questions people ask
How do you find the median of a row-wise sorted matrix efficiently?
Binary search on the value. For a guess x, count entries at most x with an upper-bound search in each row; the median is the smallest x whose count reaches half the entries plus one.
What is the time complexity of the binary search solution?
O(R log C log M) for R rows, C columns and a value range of size M, with O(1) extra space. Sorting all entries instead costs O(RC log RC) time and O(RC) memory.
Why is the answer always a value that is in the matrix?
The count of entries at most x only changes when x reaches an existing value. The smallest x with a big enough count must therefore be one of the entries.
What if the matrix has an even number of entries?
Then there are two middle values. Agree on the definition with the interviewer, then find each middle rank with the same counting search and combine them as agreed.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
