Matrix Median

Asked atJ.P. Morgan
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given a 2D array **matrix **that is row-wise sorted. The task is to find the median of the given matrix.

Input: matrix=[ [1, 4, 9], [2, 5, 6], [3, 7, 8] ] Output: 5 Explanation: If we find the linear sorted array, the array becomes 1 2 3 4 5 6 7 8 9. So, median = 5

Input: matrix=[ [1, 3, 8], [2, 3, 4], [1, 2, 5] ] Output: 3 Explanation: If we find the linear sorted array, the array becomes 1 1 2 2 3 3 4 5 8. So, median = 3

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

  • N==matrix.size
  • M==matrix[0].size
  • 1 <= N, M <= 105
  • 1 <= N*M <= 106
  • 1 <= matrix[i] <= 109
  • N*M is odd

cpp

class Solution{
public:
    int findMedian(vector<vector<int>>&matrix) {
      
    }
};

java

class Solution {
    public int findMedian(int[][] matrix) {
      
    }
}

python

class Solution:
    def findMedian(self, matrix):

javascript

class Solution {
    findMedian(matrix) {
       
    }
}

csharp

class Solution {
    public int FindMedian(List<List<int>> matrix) {

    }
}

go

func findMedian(matrix [][]int) int {
	//your code goes here
}
Stuck? Show a way to structure it+
  1. 01Search the value range, not coordinates.
  2. 02For a midpoint, count elements less than or equal to it in each row.
  3. 03Use upper bound within every sorted row.
  4. 04Move low or high based on the target rank.
  5. 05Return the first value with sufficient count.

Reference answer

Then expect these follow-ups

  • How would a heap-based solution compare?

    Tests: tradeoffs

  • How do duplicates affect the predicate?

    Tests: binary-search correctness

Hiring now

Software engineer roles are open right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior Software Engineer -.NET

    Tyler Technologies · Annapolis, Maryland

  • Software Development Engineer II

    SaaS Labs · Bengaluru, Karnataka, India

  • Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)

    Metropolitan Transportation Authority · New York, NY

Or practice this question first

Next question