Matrix Median InterviewBit Solution
Problem: Matrix Median
Problem Description:
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.
Input Format
The first and only argument given is the integer matrix A.
Output Format
Return the overall median of the matrix A.
Constraints
1 <= N, M <= 10^5
1 <= N*M <= 10^6
1 <= A[i] <= 10^9
N*M is odd
For Example
Input 1:
A = [ [1, 3, 5],
[2, 6, 9],
[3, 6, 9] ]
Output 1:
5
Explanation 1:
A = [1, 2, 3, 3, 5, 6, 6, 9, 9]
Median is 5. So, we return 5.
Input 2:
A = [ [5, 17, 100] ]
Output 2:
17
Approach
In this problem, the rows are sorted, but we don't have any information on the columns.
So we can do binary search on range from minimum value of the matrix to the maximum value of the matrix. And for each mid-value, we can iterate through the row and will find how many elements are smaller than the current element. If the number of elements exceeds the (total number of the matrix) / 2, then that means we have to shift towards the right side, otherwise the left side.
Time & Space Complexity
Time Complexity: O(NlogM)
- N is the number of rows, and M is the difference between the minimum and the maximum value of the matrix.
Space Complexity: O(1)
- Ignoring the input matirx, we have not taken any extra space to solve this problem.
Solution:
Code in C++
Comments