Problem Description
Given an m x n matrix where every row is sorted in non-decreasing order and the total number of elements is odd, return the median of the matrix. The challenge is to accomplish this in less than O(m * n) time complexity.
Key Insights
- Each row of the matrix is individually sorted, allowing efficient binary search operations.
- Instead of merging rows or flattening the matrix, we can perform binary search on the value range (from the minimum element to the maximum element in the matrix).
- For every candidate value during the binary search over the answer range, we can count how many elements in the matrix are less than or equal to it using binary search on each row.
- The median is the smallest number for which the count of elements less than or equal to it is at least (m * n // 2 + 1).
Space and Time Complexity
Time Complexity: O(m * log(n) * log(max - min)) Space Complexity: O(1)
Solution
We use a binary search on the value range of the matrix. First, determine the minimum (from the first element of each row) and maximum (from the last element of each row) values. Then use binary search as follows:
- Calculate mid = (low + high) / 2.
- For each row, count the number of elements no greater than mid using binary search.
- Sum these counts across all rows.
- If the total count is less than (m*n//2 + 1), adjust the low pointer to mid + 1; otherwise, adjust the high pointer to mid - 1.
- Continue until low exceeds high. The current low will be the median. The main trick is to perform binary search twice: once on the value range and once on each row, keeping the overall time complexity efficient.