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
Matrix Median: Find Middle Element EfficientlyInput Matrix135269369Each row sortedConceptualSortAll Elements Sorted123356699012345678Indices (median at 4)5Median9 elements total → median at position 9÷2 = 4 (0-indexed)Binary search on values finds 5 without sorting all elements💡 Key Insight: Search on answer space [min, max]Count elements ≤ candidate value instead of sorting
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
Asked in
Google 25 Microsoft 20 Amazon 18 Facebook 15
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen