GeeksforGeeks Medium

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.

Constraints
  • 1 <= n, m <= 400
  • n and m are both odd
  • 1 <= mat[i][j] <= 2000
  • Each row is sorted in non-decreasing order
binary-searchmatrix
Open on GeeksforGeeks ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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).

1

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.

2

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).

3

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.

4

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.

04

Code in Python, C++ and Java

▶1from bisect import bisect_right
▶2 
▶3class Solution:
▶4 def median(self, mat):
▶5 n, m = len(mat), len(mat[0])
▶6 half = n * m // 2
▶7 lo = min(row[0] for row in mat)
▶8 hi = max(row[-1] for row in mat)
▶9 while lo < hi:
▶10 mid = (lo + hi) // 2
▶11 count = 0
▶12 for row in mat:
▶13 count += bisect_right(row, mid)
▶14 if count <= half:
▶15 lo = mid + 1
▶16 else:
▶17 hi = mid
▶18 return lo
range1lomid9hiat most midmat135269369totalvs4halfthe median is a value from 1 to 9
lo1smallest first entry
hi9largest last entry
half43 × 3 = 9 entries
Every row is sorted, so the smallest entry sits in the first column and the largest in the last. The median lies between 1 and 9. With 9 entries, exactly 4 come before the median in sorted order.
range1lo5mid9hiat most midmat1353269369total3vs4halfrow 0 has 3 entries at most 5
mid5guess for the median
count3rows 0 to 0
Try 5, the middle of 1 to 9. Row 0 is sorted, so one binary search finds where entries larger than 5 start: past the end, so all 3 count. Running total: 3.
range1lo5mid9hiat most midmat13532691369total4vs4halfrow 1 has 1 entry at most 5
mid5guess for the median
count4rows 0 to 1
Row 1 is sorted, so one binary search finds where entries larger than 5 start: after 1 entry. Running total: 4.
range1lo5mid9hiat most midmat135326913691total5vs4halfrow 2 has 1 entry at most 5
mid5guess for the median
count5rows 0 to 2
Row 2 is sorted, so one binary search finds where entries larger than 5 start: after 1 entry. Running total: 5.
range1lo5mid5hiat most midmat135326913691total5>4half5 entries at most 5, over half → hi moves to 5
count5half = 4
hi5
5 entries are at most 5, more than 4, so the median is 5 or smaller. 5 stays in the range, because it may be the median itself. The range is now 1 to 5.
range1lo3mid5hiat most midmat1352269369total2vs4halfrow 0 has 2 entries at most 3
mid3guess for the median
count2rows 0 to 0
Try 3, the middle of 1 to 5. Row 0 is sorted, so one binary search finds where entries larger than 3 start: after 2 entries. Running total: 2.
range1lo3mid5hiat most midmat13522691369total3vs4halfrow 1 has 1 entry at most 3
mid3guess for the median
count3rows 0 to 1
Row 1 is sorted, so one binary search finds where entries larger than 3 start: after 1 entry. Running total: 3.
range1lo3mid5hiat most midmat135226913691total4vs4halfrow 2 has 1 entry at most 3
mid3guess for the median
count4rows 0 to 2
Row 2 is sorted, so one binary search finds where entries larger than 3 start: after 1 entry. Running total: 4.
range4lo3mid5hiat most midmat135226913691total4≤4half4 entries at most 3, not over half → lo moves to 4
count4half = 4
lo4
Only 4 entries are at most 3, not more than 4, so the median is larger than 3. The range shrinks to 4 to 5.
range4lo4mid5hiat most midmat1352269369total2vs4halfrow 0 has 2 entries at most 4
mid4guess for the median
count2rows 0 to 0
Try 4, the middle of 4 to 5. Row 0 is sorted, so one binary search finds where entries larger than 4 start: after 2 entries. Running total: 2.
range4lo4mid5hiat most midmat13522691369total3vs4halfrow 1 has 1 entry at most 4
mid4guess for the median
count3rows 0 to 1
Row 1 is sorted, so one binary search finds where entries larger than 4 start: after 1 entry. Running total: 3.
range4lo4mid5hiat most midmat135226913691total4vs4halfrow 2 has 1 entry at most 4
mid4guess for the median
count4rows 0 to 2
Row 2 is sorted, so one binary search finds where entries larger than 4 start: after 1 entry. Running total: 4.
range5lo4mid5hiat most midmat135226913691total4≤4half4 entries at most 4, not over half → lo moves to 5
count4half = 4
lo5
Only 4 entries are at most 4, not more than 4, so the median is larger than 4. The range shrinks to 5 to 5.
range5lomid5hiat most midmat135269369totalvs4halflo meets hi → median 5
return5
5 is the smallest value with more than 4 entries at most itself, so it is the median. It is a real entry: the count only rises at values that are in the matrix, so the smallest value that passes half must be one of them.
05

Common pitfalls

Counting entries strictly below mid

✗ Wrong
count += bisect_left(row, mid)
✓ Right
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

✗ Wrong
else:
    hi = mid - 1
✓ Right
else:
    hi = mid

A 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.

06

Edge cases

A single column

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.

Every entry is the same

lo and hi start equal, so the loop never runs and that value is returned.

07

Complexity

Time
O(n · log m · log R)
Space
O(1)
R is the value range, at most 2,000 here, so the search takes about 11 rounds. Each round runs one O(log m) binary search per row. Finding lo and hi reads two entries per row.
08

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.