Matrix Median
The problem
Given a 2D array **matrix **that is row-wise sorted. The task is to find the median of the given matrix.
Input: matrix=[ [1, 4, 9], [2, 5, 6], [3, 7, 8] ] Output: 5 Explanation: If we find the linear sorted array, the array becomes 1 2 3 4 5 6 7 8 9. So, median = 5
Input: matrix=[ [1, 3, 8], [2, 3, 4], [1, 2, 5] ] Output: 3 Explanation: If we find the linear sorted array, the array becomes 1 1 2 2 3 3 4 5 8. So, median = 3
Input: matrix=[ [1, 4, 15], [2, 5, 6], [3, 8, 11] ]
- N==matrix.size
- M==matrix[0].size
- 1 <= N, M <= 105
- 1 <= N*M <= 106
- 1 <= matrix[i] <= 109
- N*M is odd
cpp
class Solution{
public:
int findMedian(vector<vector<int>>&matrix) {
}
};java
class Solution {
public int findMedian(int[][] matrix) {
}
}python
class Solution:
def findMedian(self, matrix):javascript
class Solution {
findMedian(matrix) {
}
}csharp
class Solution {
public int FindMedian(List<List<int>> matrix) {
}
}go
func findMedian(matrix [][]int) int {
//your code goes here
}Stuck? Show a way to structure it+
- 01Search the value range, not coordinates.
- 02For a midpoint, count elements less than or equal to it in each row.
- 03Use upper bound within every sorted row.
- 04Move low or high based on the target rank.
- 05Return the first value with sufficient count.
Reference answer
Then expect these follow-ups
How would a heap-based solution compare?
Tests: tradeoffs
How do duplicates affect the predicate?
Tests: binary-search correctness
Hiring now
Software engineer roles are open right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Software Engineer, ROS Open Platform & AI Enablement
Roblox · San Mateo, CA, United States

Senior Software Engineer I - Data Engineering
Rocket Lab · Long Beach, CA

Principal Embedded Software Engineer
BAE Systems · Endicott, New York, United States
Next question