Find median in row wise sorted matrix
Last Updated :
23 Jul, 2025
Given a row-wise sorted matrix mat[][] of order n * m, where the number of rows and columns are always odd. The task is to find the median of the matrix.
Note: Median is the middle number in a sorted ascending or descending list of numbers. In case of an even number of elements return the left median.
Examples:
Input: mat[][] = [[1 3 5],
[2 6 9],
[3 6 9]]
Output: 5
Explanation: Elements in sorted order: 1 2 3 3 5 6 6 9 9. There are total 9 elements, thus the median is the element at index 5 (1-based) i.e. 5.
Input: mat[][] = [[1 3 4],
[2 5 6]
[3 7 9]]
Output: 4
Explanation: Elements in sorted order: 1 2 3 3 4 5 6 7 9. There are total 9 elements, thus the median is the element at index 5 (1-based) i.e. 4.
The idea is to store all the elements of the given matrix in a new array of size r x c. Then sort the array and find the median element.
Below is given the implementation:
C++
// C++ program to find median of a matrix
// Using Extra Space
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int median(vector<vector<int>> &mat) {
// Flatten the matrix into a 1D array
vector<int> arr;
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[0].size(); j++) {
arr.push_back(mat[i][j]);
}
}
// Sort the array
sort(arr.begin(), arr.end());
// Find the median element
int mid = arr.size() / 2;
return arr[mid];
}
int main() {
vector<vector<int>> matrix = {{1, 3, 5}, {2, 6, 9}, {3, 6, 9}};
cout << median(matrix) << endl;
return 0;
}
Java
// Java program to find median of a matrix
// Using Extra Space
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class GfG {
static int median(int mat[][]) {
// Flatten the matrix into a 1D array
List<Integer> list = new ArrayList<>();
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
list.add(mat[i][j]);
}
}
// Sort the list
Collections.sort(list);
// Find and return the median element
int mid = list.size() / 2;
return list.get(mid);
}
public static void main(String[] args) {
int[][] matrix = {
{1, 3, 5},
{2, 6, 9},
{3, 6, 9}
};
System.out.println(median(matrix));
}
}
Python
# python3 program to find median of a matrix
# Using Extra Space
def median(mat):
# Flatten the matrix into a 1D array
arr = []
for i in range(len(mat)):
for j in range(len(mat[0])):
arr.append(mat[i][j])
# Sort the array
arr.sort()
# Find the median element
mid = len(arr) // 2
return arr[mid]
if __name__ == "__main__":
mat = [[1, 3, 5],
[2, 6, 9],
[3, 6, 9]]
print(median(mat))
C#
// C# program to find median of a matrix
// Using Extra Space
using System;
using System.Collections.Generic;
using System.Linq;
class GfG {
static int median(int[][] mat) {
// Flatten the matrix into a 1D list
List<int> arr = new List<int>();
for (int i = 0; i < mat.Length; i++) {
for (int j = 0; j < mat[i].Length; j++) {
arr.Add(mat[i][j]);
}
}
// Sort the array
arr.Sort();
// Find the median element
int mid = arr.Count / 2;
return arr[mid];
}
static void Main(string[] args) {
int[][] mat = new int[][] { new int[] { 1, 3, 5 },
new int[] { 2, 6, 9 },
new int[] { 3, 6, 9 } };
Console.WriteLine(median(mat));
}
}
JavaScript
// JavaScript program to find median of a matrix
// Using Extra Space
function median(mat) {
// Flatten the matrix into a 1D array
const arr = mat.reduce((acc, row) => acc.concat(row), []);
// Sort the array
arr.sort((a, b) => a - b);
// Find the median element
const mid = Math.floor(arr.length / 2);
return arr[mid];
}
// Driver Code
const mat = [
[1, 3, 5],
[2, 6, 9],
[3, 6, 9]
];
console.log(median(mat));
Time complexity: O(n * m * log(n * m))
Auxiliary Space: O(n * m)
[Better Approach] - Using Priority Queue - O(n * m * log(n)) Time and O(n) Space
The idea is to use min heap to find the first (n * m) / 2 smallest element and print the element at index (n * m) / 2. To do so, create a min heap using priority queue, where each element is an array that stores, mat[i][j] and its indices i.e. i & j. Now, firstly push elements of 0th column of each row in the queue. Also, declare a variable cnt to store the count of elements selected. Run a while loop until the cnt is less than or equal to (n * m) / 2, and in each iteration take out the top element of queue, storing the smallest element, let it be mat[row][col], increment cnt by 1 and push the mat[row][col+1] in the queue, which is the next greater element. After the loops end, return the last element stored in queue.
Below is given the implementation:
C++
// C++ program to find median of a matrix
// using Priority Queue
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int median(vector<vector<int>> &mat) {
int r = mat.size();
int c = mat[0].size();
priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>,
greater<pair<int, pair<int, int>>>> minHeap;
int cnt = 0, res = -1;
// calculate median index
int mid = (r * c) / 2;
// Push the first element of each row into the min-heap
for (int i = 0; i < r; i++) {
minHeap.push({mat[i][0], {i, 0}});
}
// Extract elements from the min-heap to find the median
while (cnt <= mid) {
auto top = minHeap.top();
minHeap.pop();
int row = top.second.first;
int col = top.second.second;
res = top.first;
cnt++;
// If there are more elements in the row, push the next element
if (col + 1 < c) {
minHeap.push({mat[row][col + 1], {row, col + 1}});
}
}
return res;
}
int main() {
vector<vector<int>> matrix = {{1, 3, 5}, {2, 6, 9}, {3, 6, 9}};
cout << median(matrix);
return 0;
}
Java
// Java program to find median of a matrix
// using Priority Queue
import java.util.Comparator;
import java.util.PriorityQueue;
class GfG {
static int median(int[][] mat) {
int r = mat.length;
int c = mat[0].length;
// Min-Heap to store elements
PriorityQueue<int[]> minHeap = new PriorityQueue<>(
(a, b) -> Integer.compare(a[0], b[0])
);
int cnt = 0, res = -1;
// Calculate median index
int mid = (r * c) / 2;
// Push the first element of each row into the min-heap
for (int i = 0; i < r; i++) {
minHeap.offer(new int[]{mat[i][0], i, 0});
}
// Extract elements from the min-heap to find the median
while (cnt <= mid) {
int[] top = minHeap.poll();
int row = top[1];
int col = top[2];
res = top[0];
cnt++;
// If there are more elements in the row, push the next element
if (col + 1 < c) {
minHeap.offer(new int[]{mat[row][col + 1], row, col + 1});
}
}
return res;
}
public static void main(String[] args) {
int[][] mat = {{1, 3, 5}, {2, 6, 9}, {3, 6, 9}};
System.out.println(median(mat));
}
}
Python
# python3 program to find median of a matrix
# Using Priority queue
import heapq
def median(mat):
r = len(mat)
c = len(mat[0])
# Min-Heap to store elements
minHeap = []
cnt = 0
res = -1
# Calculate median index
mid = (r * c) // 2
# Push the first element of each row into the min-heap
for i in range(r):
heapq.heappush(minHeap, (mat[i][0], i, 0))
# Extract elements from the min-heap to find the median
while cnt <= mid:
val, row, col = heapq.heappop(minHeap)
res = val
cnt += 1
# If there are more elements in the row, push the next element
if col + 1 < c:
heapq.heappush(minHeap, (mat[row][col + 1], row, col + 1))
return res
if __name__ == "__main__":
matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]]
print(median(matrix))
JavaScript
// Javascript program to find median of a matrix
// Using Priority queue
class PriorityQueue {
constructor() {
this.heap = [];
}
enqueue(value, row, col) {
this.heap.push({ value, row, col });
// Min-heap based on value
this.heap.sort((a, b) => a.value - b.value);
}
dequeue() {
// Remove and return the smallest element
return this.heap.shift();
}
isEmpty() {
return this.heap.length === 0;
}
}
function median(mat) {
let r = mat.length;
let c = mat[0].length;
let minHeap = new PriorityQueue();
let cnt = 0;
let res = -1;
// Calculate the median index
let mid = Math.floor((r * c) / 2);
// Push the first element of each row into the priority queue
for (let i = 0; i < r; i++) {
minHeap.enqueue(mat[i][0], i, 0);
}
// Extract elements from the priority queue to find the median
while (cnt <= mid) {
let { value, row, col } = minHeap.dequeue();
res = value;
cnt++;
// If there are more elements in the row, push the next element
if (col + 1 < c) {
minHeap.enqueue(mat[row][col + 1], row, col + 1);
}
}
return res;
}
// Driver code
let mat = [
[1, 3, 5],
[2, 6, 9],
[3, 6, 9]
];
console.log(median(mat));
Time complexity: O(( n * m)/2 * log(n) ), since we are going to insert and remove the top element in priority queue (n * m)/2 times and every time the priority queue will be having elements in it.
Auxiliary Space: O(n), the min-heap stores at most one element per row of the matrix at any point in time.
[Expected Approach] - Using Binary Search - O(n * log(m) * log(maxVal - minVal)) Time and O(1) Space
An efficient approach for this problem is to use binary search algorithm. The idea is that for a number x to be median there should be exactly r * c / 2 numbers that are less than this number. So, we apply binary search on search space [minimum Element to maximum Element] and try to find the count of numbers less than mid. If this count is less than r * c / 2 then search in upper half to increase the count, otherwise search in lower half to decrease the count.
Below is given the implementation:
C++
// C++ program to find median of a matrix
// using binary search
#include <algorithm>
#include <iostream>
#include <climits>
#include <vector>
using namespace std;
// Function to find the median in the matrix
int median(vector<vector<int>> &mat) {
int r = mat.size();
int c = mat[0].size();
int minVal = INT_MAX, maxVal = INT_MIN;
// Finding the minimum and maximum elements in the matrix
for (int i = 0; i < r; i++) {
if (mat[i][0] < minVal)
minVal = mat[i][0];
if (mat[i][c - 1] > maxVal)
maxVal = mat[i][c - 1];
}
int desired = (r * c + 1) / 2;
int lo = minVal, hi = maxVal;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
int place = 0;
// Count elements smaller than or equal to mid
for (int i = 0; i < r; ++i)
place += upper_bound(mat[i].begin(), mat[i].end(), mid)
- mat[i].begin();
// Adjust the range based on the count of elements found
if (place < desired)
lo = mid + 1;
else
hi = mid;
}
return lo;
}
int main() {
vector<vector<int>> mat = {{1, 3, 5}, {2, 6, 9}, {3, 6, 9}};
cout << median(mat) << endl;
return 0;
}
Java
// Java program to find median of a matrix
// using binary search
import java.util.Arrays;
class GfG {
// Function to find median in the matrix using binary search
static int median(int mat[][]) {
int n = mat.length;
int m = mat[0].length;
// Initializing the minimum and maximum values
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
// Iterating through each row of the matrix
for (int i = 0; i < n; i++) {
// Updating the minimum value if current element is smaller
if (mat[i][0] < min)
min = mat[i][0];
// Updating the maximum value if current element is larger
if (mat[i][m - 1] > max)
max = mat[i][m - 1];
}
// Calculating the desired position of the median
int desired = (n * m + 1) / 2;
// Using binary search to find the median value
while (min < max) {
// Calculating the middle value
int mid = min + (max - min) / 2;
// Counting the number of elements less than or equal to mid
int place = 0;
for (int i = 0; i < n; i++) {
place += upperBound(mat[i], mid);
}
// Updating the search range based on the count
if (place < desired) {
min = mid + 1;
} else {
max = mid;
}
}
// Returning the median value
return min;
}
// Helper function to find the upper bound of a number in a row
static int upperBound(int[] row, int num) {
int low = 0, high = row.length;
while (low < high) {
int mid = low + (high - low) / 2;
if (row[mid] <= num) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
public static void main(String[] args) {
int mat[][] = { { 1, 3, 5 },
{ 2, 6, 9 },
{ 3, 6, 9 }};
System.out.println(median(mat));
}
}
Python
# python3 program to find median of a matrix
# using binary search
from bisect import bisect_right
def median(mat):
r = len(mat)
c = len(mat[0])
minVal = float('inf')
maxVal = float('-inf')
# Finding the minimum and maximum elements in the matrix
for i in range(r):
minVal = min(minVal, mat[i][0])
maxVal = max(maxVal, mat[i][c - 1])
desired = (r * c + 1) // 2
lo = minVal
hi = maxVal
# Binary search to find the median
while lo < hi:
mid = lo + (hi - lo) // 2
place = 0
# Count elements smaller than or equal to mid using bisect_right
for i in range(r):
place += bisect_right(mat[i], mid)
if place < desired:
lo = mid + 1
else:
hi = mid
return lo
if __name__ == "__main__":
mat = [[1, 3, 5], [2, 6, 9], [3, 6, 9]]
print(median(mat))
C#
// C# program to find median of a matrix
// using binary search
using System;
class GfG {
// Function to find median in the matrix using binary search
static int median(int[][] mat) {
int n = mat.Length;
int m = mat[0].Length;
// Initializing the minimum and maximum values
int min = int.MaxValue, max = int.MinValue;
// Iterating through each row of the matrix
for (int i = 0; i < n; i++) {
// Updating the minimum value if current element is smaller
if (mat[i][0] < min)
min = mat[i][0];
// Updating the maximum value if current element is larger
if (mat[i][m - 1] > max)
max = mat[i][m - 1];
}
// Calculating the desired position of the median
int desired = (n * m + 1) / 2;
// Using binary search to find the median value
int lo = min, hi = max;
while (lo < hi)
{
// Calculating the middle value
int mid = lo + (hi - lo) / 2;
// Counting the number of elements less than or equal to mid
int place = 0;
for (int i = 0; i < n; i++)
place += upperBound(mat[i], mid);
// Updating the search range based on the count
if (place < desired)
lo = mid + 1;
else
hi = mid;
}
// Returning the median value
return lo;
}
// Helper function to find the upper bound of a number in a row
static int upperBound(int[] row, int num) {
int lo = 0, hi = row.Length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (row[mid] <= num)
lo = mid + 1;
else
hi = mid;
}
return lo;
}
static void Main(string[] args) {
int[][] mat = new int[][] {
new int[] { 1, 3, 5 },
new int[] { 2, 6, 9 },
new int[] { 3, 6, 9 }
};
Console.WriteLine(median(mat));
}
}
JavaScript
// JavaScript program to find median of a matrix
// using binary search
// Function to find median in the matrix using binary search
function median(mat) {
const n = mat.length;
const m = mat[0].length;
// Initializing the minimum and maximum values
let min = Number.MAX_VALUE, max = Number.MIN_VALUE;
// Iterating through each row of the matrix
for (let i = 0; i < n; i++) {
// Updating the minimum value if current element is smaller
if (mat[i][0] < min)
min = mat[i][0];
// Updating the maximum value if current element is larger
if (mat[i][m - 1] > max)
max = mat[i][m - 1];
}
// Calculating the desired position of the median
const desired = Math.floor((n * m + 1) / 2);
// Using binary search to find the median value
let lo = min, hi = max;
while (lo < hi) {
// Calculating the middle value
const mid = Math.floor(lo + (hi - lo) / 2);
// Counting the number of elements less than or equal to mid
let place = 0;
for (let i = 0; i < n; i++) {
place += upperBound(mat[i], mid);
}
// Updating the search range based on the count
if (place < desired) {
lo = mid + 1;
} else {
hi = mid;
}
}
// Returning the median value
return lo;
}
// Helper function to find the upper bound of a number in a row
function upperBound(row, num) {
let lo = 0, hi = row.length;
while (lo < hi) {
const mid = Math.floor(lo + (hi - lo) / 2);
if (row[mid] <= num) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
// Driver Code
const mat = [
[1, 3, 5],
[2, 6, 9],
[3, 6, 9]
];
console.log(median(mat));
Time Complexity: O(n * log(m) * log(maxVal - minVal)), the upper bound function will take log(m) time and is performed for each row. And binary search is performed from minVal to maxVal.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem