Talentd
FleetCode

2387. Median of a Row Wise Sorted Matrix

Medium70.9% acceptance1 companyPremium elsewhere, free here

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.

Example 1:

Input: grid = [[1,1,2],[2,3,3],[1,3,4]]
Output: 2
Explanation: The elements of the matrix in sorted order are 1,1,1,2,2,3,3,3,4. The median is 2.

Example 2:

Input: grid = [[1,1,3,3,4]]
Output: 3
Explanation: The elements of the matrix in sorted order are 1,1,3,3,4. The median is 3.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 500
  • m and n are both odd.
  • 1 <= grid[i][j] <= 106
  • grid[i] is sorted in non-decreasing order.

Asked at 1 company

Hints open one at a time

Hint 1
How can you use the fact that the rows are sorted in non-decreasing order to solve the problem efficiently?
Hint 2
Try to binary search the answer.
14:22
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[[1,1,2],[2,3,3],[1,3,4]]
Input
[[1,1,3,3,4]]
Your code is saved on this device.Solution