Problem
Given a 2D array where each row is sorted in ascending order, find the median of the entire matrix.
Examples
Example 1
|
|
Solution
Method 1 – Brute Force Merge
Intuition
The simplest way is to flatten the matrix into a single array, sort it, and pick the median. This is easy to implement but not optimal for large matrices.
Approach
- Traverse all rows and columns, collect all elements into a new array.
- Sort the array.
- Return the middle element (or average of two middle elements if total count is even).
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(mn log(mn))
, sorting all elements. - 🧺 Space complexity:
O(mn)
, storing all elements.
Method 2 – Binary Search on Value
Intuition
Since each row is sorted, we can use binary search on the value range to efficiently count how many elements are less than or equal to a candidate value, and thus find the median without flattening the matrix.
Approach
- Find the minimum and maximum values in the matrix (first and last elements of each row).
- Use binary search between min and max:
- For each mid value, count how many elements in the matrix are ≤ mid (use upper_bound/bisect in each row).
- If count < desired, move min up; else move max down.
- When min == max, that’s the median.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m log(max-min) * n)
, binary search over value range, counting in each row. - 🧺 Space complexity:
O(1)
, only counters and variables used.