Matrix Median

Binary Search 2D Arrays Hard

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

Examples:

Input: matrix=[ [1, 4, 9], [2, 5, 6], [3, 8, 7] ] 


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 7 8. So, median = 3

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

Constraints

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

Hints

  • Adjust the binary search range based on whether the count is greater or less than the desired position of the median.
  • "Since each row is sorted, count the number of elements ≤mid efficiently for each row using binary search (O(logm) per row). Sum the counts for all rows to get the total number of elements ≤ mid."

Company Tags

Optum Wayfair Riot Games Mastercard Electronic Arts Ernst & Young Docker McKinsey & Company Zynga Micron Technology IBM Zoho Roche Western Digital Etsy eBay NVIDIA Philips Healthcare Twilio PayPal Boston Consulting Group Dropbox Square Rakuten Bloomberg Google Microsoft Amazon Meta Apple Netflix Adobe