Problem
Section titled “Problem”Given a matrix of integers A of size N x M in which each row is sorted.
Find and return the overall median of matrix A.
NOTE: No extra memory is allowed.
NOTE: Rows are numbered from top to bottom and columns are numbered from left to right.
Complete the function findMedian(), which takes the matrix A and returns its median.
Example 1:
Input: A = [ [1, 3, 5], [2, 6, 9], [3, 6, 9] ]Output: 5Explanation: A = [1, 2, 3, 3, 5, 6, 6, 9, 9]Median is 5. So, we return 5.Example 2:
Input: A = [ [5, 17, 100] ]Output: 17Explanation: Median is 17.Constraints:
-
A[i] N*Mis odd
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Copying all elements and sorting them is time and memory, which the note forbids. Instead of searching for the median’s position, binary-search on its value.
Since N*M is odd, the median is the element at sorted position half = (N*M + 1) / 2 (1-based). Define count(x) = number of elements <= x. Then:
count(x)never decreases asxgrows, and- the median is the smallest
xwithcount(x) >= half: forxequal to the median, at leasthalfelements are<= x(the median and everything before it in sorted order), while for any smallerx, at mosthalf - 1are.
So we can binary-search for the smallest such x between the smallest and largest element. Because each row is sorted, count(x) for one row is just upper_bound(row, x), an binary search, and the whole count takes .
The answer found this way is always an element of the matrix: the smallest x whose count reaches half must be a value at which the count increases, i.e. a value present in A.
Algorithm
Section titled “Algorithm”- Set
loto the minimum of the first column andhito the maximum of the last column — the smallest and largest elements. - Let
half = (N * M + 1) / 2. - While
lo < hi:mid = lo + (hi - lo) / 2;cnt= sum over rows ofupper_bound(row, mid), the number of elements<= mid;- if
cnt < half, the median is larger:lo = mid + 1; otherwise it ismidor smaller:hi = mid.
- Return
lo.
Walkthrough
Section titled “Walkthrough”Example 1, half = 5. Green cells are the elements <= mid counted in that step:
Complexity
Section titled “Complexity”- Time: — where is the difference between the largest and smallest element ( for values up to ); each of those steps does
Nrow searches of . - Space: — a few counters, no copy of the matrix.
Edge cases
Section titled “Edge cases”- One row (Example 2): the count is a single
upper_bound; the search still converges on17. - All elements equal:
lo == hifrom the start, and that value is returned without iterating. - Overflow:
lo + (hi - lo) / 2avoids overflowinglo + hi, andcntis at most .
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
int Solution::findMedian(vector<vector<int> >& A) { int n = A.size(), m = A[0].size(); int lo = INT_MAX, hi = INT_MIN; for (int i = 0; i < n; i++) { lo = min(lo, A[i][0]); hi = max(hi, A[i][m - 1]); }
int half = (n * m + 1) / 2; // 1-based position of the median while (lo < hi) { int mid = lo + (hi - lo) / 2; int cnt = 0; // number of elements <= mid for (int i = 0; i < n; i++) cnt += upper_bound(A[i].begin(), A[i].end(), mid) - A[i].begin(); if (cnt < half) lo = mid + 1; else hi = mid; } return lo;}public class Solution { public int findMedian(ArrayList<ArrayList<Integer>> A) { int n = A.size(), m = A.get(0).size(); int lo = Integer.MAX_VALUE, hi = Integer.MIN_VALUE; for (List<Integer> row : A) { lo = Math.min(lo, row.get(0)); hi = Math.max(hi, row.get(m - 1)); }
int half = (n * m + 1) / 2; // 1-based position of the median while (lo < hi) { int mid = lo + (hi - lo) / 2; int cnt = 0; // number of elements <= mid for (List<Integer> row : A) cnt += upperBound(row, mid); if (cnt < half) lo = mid + 1; else hi = mid; } return lo; }
// number of elements <= x in the sorted row private int upperBound(List<Integer> row, int x) { int l = 0, r = row.size(); while (l < r) { int mid = (l + r) >>> 1; if (row.get(mid) <= x) l = mid + 1; else r = mid; } return l; }}from bisect import bisect_right
class Solution: # @param A : list of list of integers # @return an integer def findMedian(self, A): n, m = len(A), len(A[0]) lo = min(row[0] for row in A) hi = max(row[-1] for row in A)
half = (n * m + 1) // 2 # 1-based position of the median while lo < hi: mid = (lo + hi) // 2 cnt = sum(bisect_right(row, mid) for row in A) # number of elements <= mid if cnt < half: lo = mid + 1 else: hi = mid return loGive it a try first
Attempt the problem on InterviewBit — the code will still be here.




