oneby7

Binary Search Searching a matrix

258. Median of a Row Wise Sorted Matrix

Medium

You are given a grid of integers grid with m rows and n columns. Every row is sorted in non-decreasing order, and the number of cells, m · n, is odd. Return the median of all the values in the grid.

The median is the middle value once all m · n values are written out in sorted order. Equal values each take their own place in that order, so a value that appears three times takes three places.

Only the rows are sorted. The grid as a whole need not be: a row can start below the end of the row above it. Try to find the median in less than O(m · n) time.

Example 1

2511138466

Input: grid = [[2, 5, 11], [1, 3, 8], [4, 6, 6]]

Output: 5

Explanation: In sorted order the nine values are 1, 2, 3, 4, 5, 6, 6, 8, 11. The fifth of them, 5, is in the middle.

Example 2

-40779-9-4-42311111

Input: grid = [[-4, 0, 7, 7, 9], [-9, -4, -4, 2, 3], [1, 1, 1, 1, 1]]

Output: 1

Explanation: Five values are smaller than 1 and five are larger. The middle value, the eighth of 15, is one of the five 1s.

Example 3

−10⁹10⁹0

Input: grid = [[-1000000000], [1000000000], [0]]

Output: 0

Explanation: Each row holds one value, so every row is sorted. In order the values are -1000000000, 0 and 1000000000.

Check your understanding

Work out the answer for this input before you write any code.

grid = [[4, 8, 9], [1, 2, 3], [5, 6, 7]]

Constraints

  • m == grid.length, n == grid[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105, and m · n is odd.
  • -109 ≤ grid[i][j] ≤ 109
  • Each row of grid is sorted in non-decreasing order.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.