Given an m x n matrix where each row is sorted in non-decreasing order and contains an odd total number of integers, your task is to find the median of all elements in the matrix.
The median is the middle value when all elements are arranged in sorted order. Since the total count is odd, there will always be exactly one median value.
Important: You must solve this problem in less than O(m ร n) time complexity, which means you cannot simply extract all elements and sort them.
Example: In a 3ร3 matrix with 9 elements, the median would be the 5th smallest element when all 9 elements are conceptually sorted.
Input & Output
Visualization
Time & Space Complexity
Binary search on answer space: log(max-min) iterations, each taking O(m * log(n)) to count elements
Only using a few variables for binary search, no extra arrays needed
Constraints
-
m == grid.length -
n == grid[i].length -
1 โค m, n โค 500 -
m * nis odd -
1 โค grid[i][j] โค 106 - Each row is sorted in non-decreasing order