Median of a Row Wise Sorted Matrix - Problem
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.
Note: The median is the middle element when all elements are sorted in ascending order. Since the matrix contains an odd number of elements, there will always be exactly one median element.
Input & Output
Example 1 — Basic 3x3 Matrix
$
Input:
grid = [[1,3,5],[2,6,9],[3,6,9]]
›
Output:
5
💡 Note:
Sorted elements: [1,2,3,3,5,6,6,9,9]. The median (middle element at index 4) is 5.
Example 2 — Different Values
$
Input:
grid = [[1,2,3],[4,5,6],[7,8,9]]
›
Output:
5
💡 Note:
All elements in order: [1,2,3,4,5,6,7,8,9]. The median is the middle element 5 at index 4.
Example 3 — Repeated Values
$
Input:
grid = [[1,1,3],[2,2,3],[3,3,3]]
›
Output:
3
💡 Note:
Sorted: [1,1,2,2,3,3,3,3,3]. The median at position 4 (0-indexed) is 3.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 500
- m * n is odd
- 1 ≤ grid[i][j] ≤ 106
- grid[i] is sorted in non-decreasing order
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
3x3 matrix with 9 elements, each row sorted
2
Conceptual Sort
If we sorted all elements: [1,2,3,3,5,6,6,9,9]
3
Find Median
Middle element at index 4 is our answer: 5
Key Takeaway
🎯 Key Insight: Binary search on the value range rather than positions, using the sorted property to count efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code