Median of a Row Wise Sorted Matrix Problem
#2387
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2387.
Given an m x n matrix grid containing an odd number of integers where each row is sorted in non-decreasing order, return the median of the matrix.
You must solve the problem in less than O(m * n) time complexity.
Example 1:
Input: grid = [[1,1,2],[2,3,3],[1,3,4]]
Output: 2
Explanation: The elements of the matrix in sorted order are 1,1,1,2,2,3,3,3,4. The median is 2.
Example 2:
Input: grid = [[1,1,3,3,4]]
Output: 3
Explanation: The elements of the matrix in sorted order are 1,1,3,3,4. The median is 3.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 500mandnare both odd.1 <= grid[i][j] <= 10^6grid[i]is sorted in non-decreasing order.
Solution
Approach: Binary Search on the Value
The matrix has an odd number of elements, so the median is the ceil(m * n / 2)-th smallest one. Binary search over the possible values x (from 0 to 10^6): count how many elements are <= x, which takes one binary search per row because rows are sorted. If the count is at least the target, the median is x or smaller; otherwise it is larger.
Complexity: time O(m log n log M), space O(1), where m and n are the grid dimensions and M is the largest value.
from bisect import bisect_right
class Solution:
def matrixMedian(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
target = (m * n + 1) >> 1
left, right = 0, 10**6
while left < right:
mid = (left + right) >> 1
if sum(bisect_right(row, mid) for row in grid) >= target:
right = mid
else:
left = mid + 1
return left