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
Median of Row Wise Sorted Matrix INPUT 3x3 Matrix (sorted rows) 1 3 5 2 6 9 3 6 9 Total elements: 9 (odd) Median position: 5th Value Range min = 1, max = 9 Sorted: [1,2,3,3,5,6,6,9,9] Median at index 4 ALGORITHM STEPS 1 Binary Search Setup low=1, high=9, target=5 2 Calculate Mid mid = (1+9)/2 = 5 3 Count Elements <= mid Use binary search per row Row 0 [1,3,5]: 3 elements <=5 Row 1 [2,6,9]: 1 element <=5 Row 2 [3,6,9]: 1 element <=5 Total count = 5 = target 4 Adjust Search Range count >= target: high=mid else: low=mid+1 Time: O(m * log(n) * log(max-min)) FINAL RESULT Binary Search Trace Iter 1: low=1, high=9, mid=5 count=5, high=5 Iter 2: low=1, high=5, mid=3 count=4, low=4 Iter 3: low=4, high=5, mid=4 count=4, low=5 MEDIAN 5 Output 5 OK - Converged at low=high=5 Key Insight: Binary search on the answer space (min to max value). For each candidate median, count elements <= it using binary search on each sorted row. The median is the smallest value with count >= (m*n+1)/2. This achieves O(m * log(n) * log(max-min)) instead of O(m*n) for full sort. TutorialsPoint - Median of a Row Wise Sorted Matrix | Optimal Solution
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