Matrix Median

Problem and examples

Given a row-wise sorted matrix (each row is individually sorted in increasing order), your task is to find the median of all elements in the matrix.

  • The matrix contains r rows and c columns.
  • The total number of elements is always r × c.
  • If the matrix is empty (0 rows or 0 columns), the median is considered undefined or null.

The median is the element that lies in the middle of the sorted order of all matrix elements. For an odd number of elements, it's the exact middle. For an even number, return the lower middle element.

Matrix Rows × Cols Median Description
[[1, 3, 5], [2, 6, 9], [3, 6, 9]] 3 × 3 5 Sorted order: [1, 2, 3, 3, 5, 6, 6, 9, 9], middle element is 5
[[1, 3], [2, 4]] 2 × 2 2 Sorted: [1, 2, 3, 4], lower middle is 2
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 3 × 3 5 Already fully sorted matrix, 5 is the center
[[10, 20, 30], [5, 15, 25], [1, 2, 3]] 3 × 3 10 Unordered globally, but each row is sorted. Full order: [1, 2, 3, 5, 10, 15, 20, 25, 30]
[[1]] 1 × 1 1 Only one element
[[1, 2, 3]] 1 × 3 2 Single row
[[1], [2], [3]] 3 × 1 2 Single column
[] 0 × 0 null Empty matrix, no elements
[[]] 1 × 0 null One row but zero columns

Explore Find Median in Row-wise Sorted Matrix

Load an example or enter your own input. Use the player controls to follow each change.

Understanding the Problem

We are given a matrix in which each row is sorted in increasing order, but the columns may not be sorted. Our task is to find the median of all elements in this matrix.

Unlike a fully sorted array, we cannot directly access the median without extra work. Flattening and sorting the entire matrix would take O(r × c × log(r × c)) time. However, we can do better by using binary search on the value range.

This is possible because although the matrix is not globally sorted, each row is individually sorted. This allows us to use binary search within each row to efficiently count how many elements are ≤ a given value.

Step-by-Step Solution with Example

Step 1: Understand the structure of the matrix

Let's take the following matrix as an example:


[
  [1, 3, 5],
  [2, 6, 9],
  [3, 6, 9]
]

Each row is sorted, but columns are not necessarily sorted. That’s acceptable for our approach.

Step 2: Determine the search space

To apply binary search, we need a range of possible values. We choose:

  • min: the smallest first element among all rows → 1
  • max: the largest last element among all rows → 9

Step 3: Define what we are searching for

There are 9 elements in total. Since 9 is odd, we are looking for the 5th smallest element (median).

Step 4: Apply binary search on the value range

Perform binary search between min and max. For each middle value mid, count how many numbers in the matrix are ≤ mid. This is done by using binary search in each row (e.g., upper_bound logic).

Step 5: Adjust the search space based on the count

- If the count of elements ≤ mid is less than desired count (e.g., <= 4), move the search right (increase low).
- Else, move the search left (decrease high).

Step 6: Continue until the search converges

Eventually, when low > high, the low will point to the smallest value that satisfies the condition, and that will be our median.

Step 7: Apply the logic on the example


Initial range: low = 1, high = 9

mid = 5 → count = 5 → enough → go left → high = 4
mid = 2 → count = 2 → too few → go right → low = 3
mid = 3 → count = 4 → too few → go right → low = 4
mid = 4 → count = 4 → too few → go right → low = 5

Now low = 5, high = 4 → done.
Answer: Median = 5

Edge Cases

Case 1: Even number of elements


[[1, 3],
 [2, 4]] → Median can be chosen as floor of middle two = 2

Case 2: All elements same


[[7, 7],
 [7, 7]] → Median = 7

Case 3: One row


[[1, 2, 3, 4, 5]] → Median = 3

Case 4: One column


[[2], [4], [6]] → Median = 4

Case 5: Duplicates


[
  [1, 2, 2],
  [2, 2, 3],
  [3, 3, 4]
] → Median = 2

Case 6: Large values


[[100000, 100001],
 [100002, 100003]] → Median = 100001

Finally

This problem is an excellent example of using binary search on value range rather than indices. It's efficient and scalable, running in O(32 × r × log c) time due to the 32-bit integer search range and binary searches within each row.

Always check if the problem allows for binary search on values. Also, ensure the rows are sorted, as this is key to optimizing the count step efficiently.

  1. Set low = minimum element of the matrix, high = maximum element.
  2. Perform binary search in the range [low, high]:
  3. → For each mid value, count how many elements are ≤ mid using upper_bound logic for each row.
  4. → If the count is less than or equal to (r * c) / 2, move right (low = mid + 1).
  5. → Else, move left (high = mid - 1).
  6. Continue until low > high. At the end, low will be the median.

Implementation and efficiency

C implementation

#include <stdio.h>
#include <limits.h>

int countSmallerOrEqual(int row[], int size, int target) {
  int low = 0, high = size - 1;
  while (low <= high) {
    int mid = (low + high) / 2;
    if (row[mid] <= target) low = mid + 1;
    else high = mid - 1;
  }
  return low;
}

int matrixMedian(int matrix[3][3], int r, int c) {
  int low = INT_MAX, high = INT_MIN;
  for (int i = 0; i < r; i++) {
    if (matrix[i][0] < low) low = matrix[i][0];
    if (matrix[i][c - 1] > high) high = matrix[i][c - 1];
  }

  int desired = (r * c) / 2;
  while (low <= high) {
    int mid = (low + high) / 2;
    int count = 0;
    for (int i = 0; i < r; i++) {
      count += countSmallerOrEqual(matrix[i], c, mid);
    }
    if (count <= desired) low = mid + 1;
    else high = mid - 1;
  }
  return low;
}

int main() {
  int matrix[3][3] = {{1, 3, 5}, {2, 6, 9}, {3, 6, 9}};
  printf("Median is: %d\n", matrixMedian(matrix, 3, 3));
  return 0;
}

C++ implementation

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int countSmallerOrEqual(const vector<int>& row, int target) {
  return upper_bound(row.begin(), row.end(), target) - row.begin();
}

int findMedian(vector<vector<int>>& matrix, int r, int c) {
  int low = INT_MAX, high = INT_MIN;
  for (int i = 0; i < r; i++) {
    low = min(low, matrix[i][0]);
    high = max(high, matrix[i][c - 1]);
  }
  int desired = (r * c) / 2;
  while (low <= high) {
    int mid = (low + high) / 2;
    int count = 0;
    for (int i = 0; i < r; i++) {
      count += countSmallerOrEqual(matrix[i], mid);
    }
    if (count <= desired) low = mid + 1;
    else high = mid - 1;
  }
  return low;
}

int main() {
  vector<vector<int>> matrix = {{1, 3, 5}, {2, 6, 9}, {3, 6, 9}};
  cout << "Median is: " << findMedian(matrix, 3, 3) << endl;
  return 0;
}

Python implementation

import bisect

def matrix_median(matrix):
    r, c = len(matrix), len(matrix[0])
    low, high = matrix[0][0], matrix[0][-1]
    for row in matrix:
        low = min(low, row[0])
        high = max(high, row[-1])

    desired = (r * c) // 2
    while low <= high:
        mid = (low + high) // 2
        count = 0
        for row in matrix:
            count += bisect.bisect_right(row, mid)

        if count <= desired:
            low = mid + 1
        else:
            high = mid - 1

    return low

matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]]
print("Median is:", matrix_median(matrix))

Java implementation

import java.util.*;

public class MatrixMedian {
  public static int countSmallerOrEqual(int[] row, int target) {
    int low = 0, high = row.length - 1;
    while (low <= high) {
      int mid = (low + high) / 2;
      if (row[mid] <= target)
        low = mid + 1;
      else
        high = mid - 1;
    }
    return low;
  }

  public static int findMedian(int[][] matrix, int r, int c) {
    int low = Integer.MAX_VALUE, high = Integer.MIN_VALUE;
    for (int[] row : matrix) {
      low = Math.min(low, row[0]);
      high = Math.max(high, row[c - 1]);
    }

    int desired = (r * c) / 2;
    while (low <= high) {
      int mid = (low + high) / 2;
      int count = 0;
      for (int[] row : matrix) {
        count += countSmallerOrEqual(row, mid);
      }
      if (count <= desired)
        low = mid + 1;
      else
        high = mid - 1;
    }
    return low;
  }

  public static void main(String[] args) {
    int[][] matrix = {{1, 3, 5}, {2, 6, 9}, {3, 6, 9}};
    System.out.println("Median is: " + findMedian(matrix, 3, 3));
  }
}

JavaScript implementation

function countSmallerOrEqual(row, target) {
  let low = 0, high = row.length - 1;
  while (low <= high) {
    let mid = Math.floor((low + high) / 2);
    if (row[mid] <= target) low = mid + 1;
    else high = mid - 1;
  }
  return low;
}

function matrixMedian(matrix) {
  let r = matrix.length, c = matrix[0].length;
  let low = Infinity, high = -Infinity;

  for (let row of matrix) {
    low = Math.min(low, row[0]);
    high = Math.max(high, row[c - 1]);
  }

  let desired = Math.floor((r * c) / 2);
  while (low <= high) {
    let mid = Math.floor((low + high) / 2);
    let count = 0;
    for (let row of matrix) {
      count += countSmallerOrEqual(row, mid);
    }
    if (count <= desired) low = mid + 1;
    else high = mid - 1;
  }
  return low;
}

let matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]];
console.log("Median is:", matrixMedian(matrix));

Go implementation

package main

import (
  "fmt"
  "sort"
)

func countSmallerOrEqual(row []int, target int) int {
  return sort.Search(len(row), func(i int) bool { return row[i] > target })
}

func matrixMedian(matrix [][]int) int {
  r, c := len(matrix), len(matrix[0])
  low, high := matrix[0][0], matrix[0][c-1]
  for _, row := range matrix {
    if row[0] < low {
      low = row[0]
    }
    if row[c-1] > high {
      high = row[c-1]
    }
  }

  desired := (r * c) / 2
  for low <= high {
    mid := (low + high) / 2
    count := 0
    for _, row := range matrix {
      count += countSmallerOrEqual(row, mid)
    }
    if count <= desired {
      low = mid + 1
    } else {
      high = mid - 1
    }
  }
  return low
}

func main() {
  matrix := [][]int{{1, 3, 5}, {2, 6, 9}, {3, 6, 9}}
  fmt.Println("Median is:", matrixMedian(matrix))
}

Rust implementation

fn count_smaller_or_equal(row: &Vec<i32>, target: i32) -> usize {
  row.iter().take_while(|&x| *x <= target).count()
}

fn matrix_median(matrix: &Vec<Vec<i32>>) -> i32 {
  let r = matrix.len();
  let c = matrix[0].len();
  let mut low = matrix[0][0];
  let mut high = matrix[0][c - 1];

  for row in matrix.iter() {
    low = low.min(row[0]);
    high = high.max(row[c - 1]);
  }

  let desired = (r * c) / 2;
  while low <= high {
    let mid = (low + high) / 2;
    let mut count = 0;
    for row in matrix.iter() {
      count += count_smaller_or_equal(row, mid);
    }
    if count <= desired {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  low
}

fn main() {
  let matrix = vec![vec![1, 3, 5], vec![2, 6, 9], vec![3, 6, 9]];
  println!("Median is: {}", matrix_median(&matrix));
}

Kotlin implementation

fun countSmallerOrEqual(row: IntArray, target: Int): Int {
  var low = 0
  var high = row.size - 1
  while (low <= high) {
    val mid = (low + high) / 2
    if (row[mid] <= target) low = mid + 1 else high = mid - 1
  }
  return low
}

fun matrixMedian(matrix: Array<IntArray>): Int {
  var low = matrix[0][0]
  var high = matrix[0].last()
  for (row in matrix) {
    low = minOf(low, row.first())
    high = maxOf(high, row.last())
  }
  val desired = (matrix.size * matrix[0].size) / 2
  while (low <= high) {
    val mid = (low + high) / 2
    var count = 0
    for (row in matrix) {
      count += countSmallerOrEqual(row, mid)
    }
    if (count <= desired) low = mid + 1 else high = mid - 1
  }
  return low
}

fun main() {
  val matrix = arrayOf(intArrayOf(1, 3, 5), intArrayOf(2, 6, 9), intArrayOf(3, 6, 9))
  println("Median is: ${matrixMedian(matrix)}")
}

Swift implementation

func countSmallerOrEqual(_ row: [Int], _ target: Int) -> Int {
  var low = 0, high = row.count - 1
  while low <= high {
    let mid = (low + high) / 2
    if row[mid] <= target {
      low = mid + 1
    } else {
      high = mid - 1
    }
  }
  return low
}

func matrixMedian(_ matrix: [[Int]]) -> Int {
  let r = matrix.count, c = matrix[0].count
  var low = matrix[0][0], high = matrix[0][c - 1]
  for row in matrix {
    low = min(low, row[0])
    high = max(high, row[c - 1])
  }

  let desired = (r * c) / 2
  while low <= high {
    let mid = (low + high) / 2
    var count = 0
    for row in matrix {
      count += countSmallerOrEqual(row, mid)
    }
    if count <= desired {
      low = mid + 1
    } else {
      high = mid - 1
    }
  }
  return low
}

let matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]]
print("Median is: \(matrixMedian(matrix))")

TypeScript implementation

function countSmallerOrEqual(row: number[], target: number): number {
  let low = 0, high = row.length - 1;
  while (low <= high) {
    let mid = Math.floor((low + high) / 2);
    if (row[mid] <= target) low = mid + 1;
    else high = mid - 1;
  }
  return low;
}

function matrixMedian(matrix: number[][]): number {
  let r = matrix.length, c = matrix[0].length;
  let low = Infinity, high = -Infinity;
  for (let row of matrix) {
    low = Math.min(low, row[0]);
    high = Math.max(high, row[c - 1]);
  }

  let desired = Math.floor((r * c) / 2);
  while (low <= high) {
    let mid = Math.floor((low + high) / 2);
    let count = 0;
    for (let row of matrix) {
      count += countSmallerOrEqual(row, mid);
    }
    if (count <= desired) low = mid + 1;
    else high = mid - 1;
  }
  return low;
}

const matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]];
console.log("Median is:", matrixMedian(matrix));

Time complexity

CaseTimeExplanation
best caseO(r * log(max - min))Where r is the number of rows, and binary search runs over the value range from min to max element.
average caseO(r * log(max - min) * log c)Each iteration performs binary search across each row using upper_bound (O(log c)).
worst caseO(r * log(max - min) * log c)Full binary search over value range with upper_bound on all rows in each step.

Space complexity

O(1)

No extra space is used beyond loop variables and counters.