Kth smallest element in a row-wise and column-wise sorted 2D array
Given an n x n matrix, every row and column is sorted in non-decreasing order. Given a number K where K lies in the range [1, n*n], find the Kth smallest element in the given 2D matrix.
Example:
Input: mat ={{10, 20, 30, 40},
{15, 25, 35, 45},
{24, 29, 37, 48},
{32, 33, 39, 50 }}
K = 3
Output: 20
Explanation: The 3rd smallest element is 20
Input: mat ={{10, 20, 30, 40},
{15, 25, 35, 45},
{24, 29, 37, 48},
{32, 33, 39, 50 }}
K = 7
Output: 30
Explanation: The 7th smallest element is 30
Table of Content
[Naive Approach] – Using Sorting – O(N2 * log(N2)) Time and O(N) Space
Initialize a 1-dimensional array of size n*n to store all the elements of the mat[][] , we will get our kth minimum element by sorting the 1-dimensional array in non-decreasing order.
Below is the implementation of the above approach:
//C++ program to find the Kth smallest element
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Function to find the kth smallest element in a sorted 2D
// matrix
int findKthSmallest(vector<vector<int> >& matrix, int k)
{
int n = matrix.size();
// Create a vector to store all elements
vector<int> elements;
// Store all elements of the matrix into the vector
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
elements.push_back(matrix[i][j]);
}
}
// Sort the vector
sort(elements.begin(), elements.end());
// Return the kth smallest element (1-based index, hence
// k-1)
return elements[k - 1];
}
int main()
{
// Define the sorted 2D matrix
vector<vector<int> > matrix
= { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } };
int k = 8;
int result = findKthSmallest(matrix, k);
cout << "The " << k
<< "th smallest element is: " << result << endl;
return 0;
}
//Java program to find the Kth smallest element
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GFG {
// Function to find the kth smallest element in a sorted 2D matrix
public static int findKthSmallest(int[][] matrix, int k) {
int n = matrix.length;
// Create a list to store all elements
List<Integer> elements = new ArrayList<>();
// Store all elements of the matrix into the list
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
elements.add(matrix[i][j]);
}
}
// Sort the list
Collections.sort(elements);
// Return the kth smallest element (1-based index, hence k-1)
return elements.get(k - 1);
}
public static void main(String[] args) {
// Define the sorted 2D matrix
int[][] matrix = {
{1, 5, 9},
{10, 11, 13},
{12, 13, 15}
};
// Find the 8th smallest element
int k = 8;
int result = findKthSmallest(matrix, k);
System.out.println("The " + k + "th smallest element is: " + result);
}
}
#Python program to find the Kth smallest element
def find_kth_smallest(matrix, k):
# Create a list to store all elements
elements = []
# Store all elements of the matrix into the list
for row in matrix:
elements.extend(row)
# Sort the list
elements.sort()
# Return the kth smallest element (1-based index, hence k-1)
return elements[k - 1]
# Define the sorted 2D matrix
matrix = [
[1, 5, 9],
[10, 11, 13],
[12, 13, 15]
]
# Find the 8th smallest element
k = 8
result = find_kth_smallest(matrix, k)
print(f"The {k}th smallest element is: {result}")
//C# program to find the Kth smallest element
using System;
using System.Collections.Generic;
class Program
{
// Function to find the kth smallest element in a sorted 2D matrix
static int FindKthSmallest(int[,] matrix, int k)
{
int n = matrix.GetLength(0);
// Create a list to store all elements
List<int> elements = new List<int>();
// Store all elements of the matrix into the list
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
elements.Add(matrix[i, j]);
}
}
// Sort the list
elements.Sort();
// Return the kth smallest element (1-based index, hence k-1)
return elements[k - 1];
}
static void Main()
{
// Define the sorted 2D matrix
int[,] matrix = {
{ 1, 5, 9 },
{ 10, 11, 13 },
{ 12, 13, 15 }
};
// Find the 8th smallest element
int k = 8;
int result = FindKthSmallest(matrix, k);
// Use traditional string concatenation instead of string interpolation
Console.WriteLine("The " + k + "th smallest element is: " + result);
}
}
// Javascript program to find the Kth smallest element
function findKthSmallest(matrix, k)
{
// Create an array to store all elements
let elements = [];
// Store all elements of the matrix into the array
for (let row of matrix) {
elements.push(...row);
}
// Sort the array
elements.sort((a, b) => a - b);
// Return the kth smallest element (1-based index, hence
// k-1)
return elements[k - 1];
}
// Define the sorted 2D matrix
const matrix =
[ [ 1, 5, 9 ], [ 10, 11, 13 ], [ 12, 13, 15 ] ];
// Find the 8th smallest element
const k = 8;
const result = findKthSmallest(matrix, k);
console.log(`The ${k}th smallest element is: ${result}`);
Output
The 8th smallest element is: 13
Time Complexity: O(N2 * log(N2)) , due to sorting of N2 elements.
Auxiliary Space : O(N2)
[Expected Approach] – Using Priority Queue – O(N2 * log(K)) Time and O(K) Space
Create a priority_queue, say max-heap to store and maintain the track of K elements in the heap. If the size of the heap exceeds more than K while inserting the elements , we will pop the top element from max-heap so as to maintain the size of K elements. After successful traversal in mat[][], the top element of the max_heap will be the Kth minimum element.
Below is the implementation of the above approach:
//C++ program to find the Kth smallest element using priority queue
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Function to find the kth smallest element in a sorted 2D
// matrix using a max-heap
int findKthSmallest(vector<vector<int> >& matrix, int k)
{
int n = matrix.size();
priority_queue<int> maxHeap;
// Traverse all elements in the matrix
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int currentElement = matrix[i][j];
// Push the current element into the max-heap
maxHeap.push(currentElement);
// If the size of the max-heap exceeds k, remove
// the largest element
if (maxHeap.size() > k) {
maxHeap.pop();
}
}
}
// The top element of the max-heap is the kth smallest
// element
return maxHeap.top();
}
int main()
{
// Define the sorted 2D matrix
vector<vector<int> > matrix
= { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } };
// Find the 8th smallest element
int k = 8;
int result = findKthSmallest(matrix, k);
cout << "The " << k
<< "th smallest element is: " << result << endl;
return 0;
}
//Java program to find the Kth smallest element using priority queue
import java.util.PriorityQueue;
public class GFG {
// Function to find the kth smallest element in a sorted
// 2D matrix using a max-heap
public static int findKthSmallest(int[][] matrix, int k)
{
int n = matrix.length;
// Max-heap to store k smallest elements
PriorityQueue<Integer> maxHeap
= new PriorityQueue<>((a, b) -> b - a);
// Traverse all elements in the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int currentElement = matrix[i][j];
// Push the current element into the
// max-heap
maxHeap.offer(currentElement);
// If the size of the max-heap exceeds k,
// remove the largest element
if (maxHeap.size() > k) {
maxHeap.poll();
}
}
}
// The top element of the max-heap is the kth
// smallest element
return maxHeap.peek();
}
public static void main(String[] args)
{
// Define the sorted 2D matrix
int[][] matrix = { { 1, 5, 9 },
{ 10, 11, 13 },
{ 12, 13, 15 } };
// Find the 8th smallest element
int k = 8;
int result = findKthSmallest(matrix, k);
System.out.println("The " + k
+ "th smallest element is: "
+ result);
}
}
#Python program to find the Kth smallest element using priority queue
import heapq
def find_kth_smallest(matrix, k):
n = len(matrix)
# Max-heap to store k smallest elements
max_heap = []
# Traverse all elements in the matrix
for i in range(n):
for j in range(n):
current_element = matrix[i][j]
# Push the current element into the max-heap
heapq.heappush(max_heap, -current_element)
# If the size of the max-heap exceeds k, remove the largest element
if len(max_heap) > k:
heapq.heappop(max_heap)
# The top element of the max-heap is the kth smallest element
return -max_heap[0]
# Define the sorted 2D matrix
matrix = [
[1, 5, 9],
[10, 11, 13],
[12, 13, 15]
]
# Find the 8th smallest element
k = 8
result = find_kth_smallest(matrix, k)
print(f"The {k}th smallest element is: {result}")
//C# program to find the Kth smallest element using priority queue
using System;
using System.Collections.Generic;
class MaxHeap<T> where T : IComparable<T>
{
private readonly List<T> _heap;
private readonly int _capacity;
public MaxHeap(int capacity)
{
_heap = new List<T>(capacity);
_capacity = capacity;
}
public int Count => _heap.Count;
public void Add(T item)
{
if (_heap.Count < _capacity)
{
_heap.Add(item);
HeapifyUp(_heap.Count - 1);
}
else if (_heap.Count > 0 && item.CompareTo(_heap[0]) < 0)
{
_heap[0] = item;
HeapifyDown(0);
}
}
public T Peek()
{
if (_heap.Count == 0)
throw new InvalidOperationException("Heap is empty.");
return _heap[0];
}
private void HeapifyUp(int index)
{
int parentIndex = (index - 1) / 2;
if (index > 0 && _heap[index].CompareTo(_heap[parentIndex]) > 0)
{
Swap(index, parentIndex);
HeapifyUp(parentIndex);
}
}
private void HeapifyDown(int index)
{
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
int largest = index;
if (leftChild < _heap.Count && _heap[leftChild].CompareTo(_heap[largest]) > 0)
{
largest = leftChild;
}
if (rightChild < _heap.Count && _heap[rightChild].CompareTo(_heap[largest]) > 0)
{
largest = rightChild;
}
if (largest != index)
{
Swap(index, largest);
HeapifyDown(largest);
}
}
private void Swap(int i, int j)
{
T temp = _heap[i];
_heap[i] = _heap[j];
_heap[j] = temp;
}
}
class Program
{
// Function to find the kth smallest element in a sorted 2D matrix using a max-heap
static int FindKthSmallest(int[,] matrix, int k)
{
int n = matrix.GetLength(0);
// Max-heap to store k smallest elements
var maxHeap = new MaxHeap<int>(k);
// Traverse all elements in the matrix
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
int currentElement = matrix[i, j];
maxHeap.Add(currentElement);
}
}
// The top element of the max-heap is the kth smallest element
return maxHeap.Peek();
}
static void Main()
{
// Define the sorted 2D matrix
int[,] matrix = {
{ 1, 5, 9 },
{ 10, 11, 13 },
{ 12, 13, 15 }
};
// Find the 8th smallest element
int k = 8;
int result = FindKthSmallest(matrix, k);
Console.WriteLine($"The {k}th smallest element is: {result}");
}
}
//Javascript program to find the Kth smallest element using priority queue
class MaxHeap {
constructor() {
this.heap = [];
}
push(val) {
this.heap.push(val);
this._heapifyUp(this.heap.length - 1);
}
pop() {
if (this.heap.length === 0) return null;
const root = this.heap[0];
const end = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = end;
this._heapifyDown(0);
}
return root;
}
peek() {
return this.heap[0] || null;
}
_heapifyUp(index) {
const element = this.heap[index];
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
const parent = this.heap[parentIndex];
if (parent >= element) break;
this.heap[index] = parent;
index = parentIndex;
}
this.heap[index] = element;
}
_heapifyDown(index) {
const length = this.heap.length;
const element = this.heap[index];
while (true) {
const leftChildIdx = 2 * index + 1;
const rightChildIdx = 2 * index + 2;
let largest = index;
if (leftChildIdx < length && this.heap[leftChildIdx] > this.heap[largest]) {
largest = leftChildIdx;
}
if (rightChildIdx < length && this.heap[rightChildIdx] > this.heap[largest]) {
largest = rightChildIdx;
}
if (largest === index) break;
this.heap[index] = this.heap[largest];
index = largest;
}
this.heap[index] = element;
}
}
// Function to find the kth smallest element in a sorted 2D matrix using a max-heap
function findKthSmallest(matrix, k) {
const n = matrix.length;
const maxHeap = new MaxHeap();
for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
const currentElement = matrix[i][j];
maxHeap.push(currentElement);
if (maxHeap.heap.length > k) {
maxHeap.pop();
}
}
}
return maxHeap.peek();
}
// Example usage
const matrix = [
[1, 5, 9],
[10, 11, 13],
[12, 13, 15]
];
const k = 8;
const result = findKthSmallest(matrix, k);
console.log(`The ${k}th smallest element is: ${result}`);
Output
The 8th smallest element is: 13
Time Complexity: O(N2* log(K)) , we will be inserting all the elements in heap one by one by maintaining the size of K elements.
Auxiliary Space : O(K)
[Expected Approach for Small Range] – Binary Search on Range – O(N* log(Max-Min)) Time and O(1) Space
This approach uses binary search to iterate over possible solutions. As answer lies in the range from mat[0][0] to mat[N-1][N-1], So we do a binary search on this range and in each iteration determine the no of elements smaller than or equal to our current middle element.

Follow the steps below to solve the problem:
- Initialize a variable, say low equals to the mat[0][0] (minimum value of matrix).
- Initialize a variable, say high equals to the mat[n-1][n-1] (maximum value of matrix).
- Initialize ans to 0.
- Perform Binary Search on the range from low to high:
- Calculate the midpoint in the range say mid.
- If the CountSmallerEqual(function which will return the count of elements less than or equal to mid) is less than k, update low to mid+ 1.
- if the returned value is greater or equal to K , this can be our possible ans. So, update ans to mid and narrow the search range by setting high to mid - 1.
- CountSmallerEqual Function (Helper function that counts the number of elements in the matrix less than or equal to the given mid.)
- Initialize a pointer, say row and col points to 0 and n-1 respectively. And a variable count = 0.
- If the mat[row][col] is greater than mid, move left in the matrix by decrementing col.
- If the mat[row][col] is less than or equal to mid, increment the count as count += col+ 1 and move down in the matrix by incrementing row.
Below is the implementation of the above approach:
//C++ program to find the Kth smallest element using Binary Serach
#include <iostream>
#include <vector>
using namespace std;
// Function to count the number of elements less than or equal to x
int countSmallerEqual(const vector<vector<int>>& matrix, int x) {
int n = matrix.size();
int count = 0;
int row = 0;
int col = n - 1;
// Traverse from the top-right corner
while (row < n && col >= 0) {
if (matrix[row][col] <= x) {
// If current element is less than or equal to x,
// all elements in this row up to the current column are <= x
count += (col + 1);
row++;
} else {
// Move left in the matrix
col--;
}
}
return count;
}
// Function to find the Kth smallest element in a sorted 2D matrix using binary search
int findKthSmallest(const vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int low = matrix[0][0];
int high = matrix[n - 1][n - 1];
int ans = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
// Count elements less than or equal to mid
int count = countSmallerEqual(matrix, mid);
if (count < k) {
// If there are less than k elements <= mid, the kth smallest is larger
low = mid + 1;
} else {
// Otherwise, mid might be the answer, but we need to check for smaller values
ans = mid;
high = mid - 1;
}
}
return ans;
}
int main() {
// Define the sorted 2D matrix
vector<vector<int>> matrix = {
{1, 5, 9},
{10, 11, 13},
{12, 13, 15}
};
// Find the Kth smallest element
int k = 8;
int result = findKthSmallest(matrix, k);
cout << "The " << k << "th smallest element is: " << result << endl;
return 0;
}
//Java program to find the Kth smallest element using Binary Serach
import java.util.Arrays;
public class GFG {
// Function to count the number of elements less than or equal to x
public static int countSmallerEqual(int[][] matrix, int x) {
int n = matrix.length;
int count = 0;
int row = 0;
int col = n - 1;
// Traverse from the top-right corner
while (row < n && col >= 0) {
if (matrix[row][col] <= x) {
// If current element is less than or equal to x,
// all elements in this row up to the current column are <= x
count += (col + 1);
row++;
} else {
// Move left in the matrix
col--;
}
}
return count;
}
// Function to find the Kth smallest element in a sorted 2D matrix using binary search
public static int findKthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int low = matrix[0][0];
int high = matrix[n - 1][n - 1];
int ans = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
// Count elements less than or equal to mid
int count = countSmallerEqual(matrix, mid);
if (count < k) {
// If there are less than k elements <= mid, the kth smallest is larger
low = mid + 1;
} else {
// Otherwise, mid might be the answer, but we need to check for smaller values
ans = mid;
high = mid - 1;
}
}
return ans;
}
public static void main(String[] args) {
// Define the sorted 2D matrix
int[][] matrix = {
{1, 5, 9},
{10, 11, 13},
{12, 13, 15}
};
// Find the Kth smallest element
int k = 8;
int result = findKthSmallest(matrix, k);
System.out.println("The " + k + "th smallest element is: " + result);
}
}
#Python program to find the Kth smallest element using Binary Serach
def count_smaller_equal(matrix, x):
n = len(matrix)
count = 0
row, col = 0, n - 1
# Traverse from the top-right corner
while row < n and col >= 0:
if matrix[row][col] <= x:
# If current element is less than or equal to x,
# all elements in this row up to the current column are <= x
count += (col + 1)
row += 1
else:
# Move left in the matrix
col -= 1
return count
def find_kth_smallest(matrix, k):
n = len(matrix)
low, high = matrix[0][0], matrix[n - 1][n - 1]
ans = 0
while low <= high:
mid = low + (high - low) // 2
# Count elements less than or equal to mid
count = count_smaller_equal(matrix, mid)
if count < k:
# If there are less than k elements <= mid, the kth smallest is larger
low = mid + 1
else:
# Otherwise, mid might be the answer, but we need to check for smaller values
ans = mid
high = mid - 1
return ans
# Define the sorted 2D matrix
matrix = [
[1, 5, 9],
[10, 11, 13],
[12, 13, 15]
]
# Find the Kth smallest element
k = 8
result = find_kth_smallest(matrix, k)
print(f"The {k}th smallest element is: {result}")
//C# program to find the Kth smallest element using Binary Serach
using System;
class GFG {
// Function to count the number of elements less than or equal to x
static int CountSmallerEqual(int[,] matrix, int x) {
int n = matrix.GetLength(0);
int count = 0;
int row = 0;
int col = n - 1;
// Traverse from the top-right corner
while (row < n && col >= 0) {
if (matrix[row, col] <= x) {
// If current element is less than or equal to x,
// all elements in this row up to the current column are <= x
count += (col + 1);
row++;
} else {
// Move left in the matrix
col--;
}
}
return count;
}
// Function to find the Kth smallest element in a sorted 2D matrix using binary search
static int FindKthSmallest(int[,] matrix, int k) {
int n = matrix.GetLength(0);
int low = matrix[0, 0];
int high = matrix[n - 1, n - 1];
int ans = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
// Count elements less than or equal to mid
int count = CountSmallerEqual(matrix, mid);
if (count < k) {
// If there are less than k elements <= mid, the kth smallest is larger
low = mid + 1;
} else {
// Otherwise, mid might be the answer, but we need to check for smaller values
ans = mid;
high = mid - 1;
}
}
return ans;
}
static void Main() {
// Define the sorted 2D matrix
int[,] matrix = {
{1, 5, 9},
{10, 11, 13},
{12, 13, 15}
};
// Find the Kth smallest element
int k = 8;
int result = FindKthSmallest(matrix, k);
Console.WriteLine("The " + k + "th smallest element is: " + result);
}
}
//Javascript program to find the Kth smallest element using Binary Serach
function countSmallerEqual(matrix, x) {
const n = matrix.length;
let count = 0;
let row = 0;
let col = n - 1;
// Traverse from the top-right corner
while (row < n && col >= 0) {
if (matrix[row][col] <= x) {
// If current element is less than or equal to x,
// all elements in this row up to the current column are <= x
count += (col + 1);
row++;
} else {
// Move left in the matrix
col--;
}
}
return count;
}
function findKthSmallest(matrix, k) {
const n = matrix.length;
let low = matrix[0][0];
let high = matrix[n - 1][n - 1];
let ans = 0;
while (low <= high) {
let mid = Math.floor(low + (high - low) / 2);
// Count elements less than or equal to mid
let count = countSmallerEqual(matrix, mid);
if (count < k) {
// If there are less than k elements <= mid, the kth smallest is larger
low = mid + 1;
} else {
// Otherwise, mid might be the answer, but we need to check for smaller values
ans = mid;
high = mid - 1;
}
}
return ans;
}
// Define the sorted 2D matrix
const matrix = [
[1, 5, 9],
[10, 11, 13],
[12, 13, 15]
];
// Find the Kth smallest element
const k = 8;
const result = findKthSmallest(matrix, k);
console.log(`The ${k}th smallest element is: ${result}`);
Output
The 8th smallest element is: 13
Time Complexity: O(2*N* log(MAX - MIN)) , where MAX and MIN are the maximum and minimum element in 2d matrix.
Auxiliary Space : O(1)