Open In App

Kth smallest element in a row-wise and column-wise sorted 2D array

Last Updated : 23 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

[Naive Approach] – Using Sorting – O(n^2 * log(n^2)) 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.

C++
// C++ program to find the Kth smallest element
#include <bits/stdc++.h>
using namespace std;

// Function to find the kth smallest 
// element in a sorted 2D matrix
int kthSmallest(vector<vector<int>>& matrix, int k) {
    int n = matrix.size();

    // Create a vector to store all elements
    vector<int> arr;

    // Store all elements of the matrix into the array
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            arr.push_back(matrix[i][j]);
        }
    }

    // Sort the array
    sort(arr.begin(), arr.end());

    // Return the kth smallest element 
    // (0-based index, hence k-1)
    return arr[k - 1];
}

int main() {
    vector<vector<int>> matrix = 
                        {{10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {24, 29, 37, 48},
                        {32, 33, 39, 50 }};
    int k = 3;
    int result = kthSmallest(matrix, k);

    cout << result << endl;

    return 0;
}
Java
// Java program to find the Kth smallest element
import java.util.*;

class GfG {
    
    // Function to find the kth smallest 
    // element in a sorted 2D matrix
    static int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;

        // Create an ArrayList to store all elements
        ArrayList<Integer> arr = new ArrayList<Integer>();

        // Store all elements of the matrix into the array
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                arr.add(matrix[i][j]);
            }
        }

        // Sort the array
        Collections.sort(arr);

        // Return the kth smallest element 
        // (0-based index, hence k-1)
        return arr.get(k - 1);
    }

    public static void main(String[] args) {
        int[][] matrix = 
                        {{10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {24, 29, 37, 48},
                        {32, 33, 39, 50}};
        int k = 3;
        int result = kthSmallest(matrix, k);

        System.out.println(result);
    }
}
Python
# Python program to find the Kth smallest element

# Function to find the kth smallest 
# element in a sorted 2D matrix
def kthSmallest(matrix, k):
    n = len(matrix)

    # Create a list to store all elements
    arr = []

    # Store all elements of the matrix into the array
    for i in range(n):
        for j in range(n):
            arr.append(matrix[i][j])

    # Sort the array
    arr.sort()

    # Return the kth smallest element 
    # (0-based index, hence k-1)
    return arr[k - 1]

if __name__ == "__main__":
    matrix = [
                        [10, 20, 30, 40],
                        [15, 25, 35, 45],
                        [24, 29, 37, 48],
                        [32, 33, 39, 50]]
    k = 3
    result = kthSmallest(matrix, k)

    print(result)
C#
// C# program to find the Kth smallest element
using System;
using System.Collections.Generic;

class GfG {
    
    // Function to find the kth smallest 
    // element in a sorted 2D matrix
    static int kthSmallest(int[,] matrix, int k) {
        int n = matrix.GetLength(0);

        // Create a List to store all elements
        List<int> arr = new List<int>();

        // Store all elements of the matrix into the array
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                arr.Add(matrix[i,j]);
            }
        }

        // Sort the array
        arr.Sort();

        // Return the kth smallest element 
        // (0-based index, hence k-1)
        return arr[k - 1];
    }

    public static void Main(string[] args) {
        int[,] matrix = 
                        {{10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {24, 29, 37, 48},
                        {32, 33, 39, 50}};
        int k = 3;
        int result = kthSmallest(matrix, k);

        Console.WriteLine(result);
    }
}
JavaScript
// JavaScript program to find the Kth smallest element

// Function to find the kth smallest 
// element in a sorted 2D matrix
function kthSmallest(matrix, k) {
    let n = matrix.length;

    // Create an array to store all elements
    let arr = [];

    // Store all elements of the matrix into the array
    for (let i = 0; i < n; ++i) {
        for (let j = 0; j < n; ++j) {
            arr.push(matrix[i][j]);
        }
    }

    // Sort the array
    arr.sort((a, b) => a - b);

    // Return the kth smallest element 
    // (0-based index, hence k-1)
    return arr[k - 1];
}

let matrix = 
                [[10, 20, 30, 40],
                [15, 25, 35, 45],
                [24, 29, 37, 48],
                [32, 33, 39, 50]];
let k = 3;
let result = kthSmallest(matrix, k);

console.log(result);

Output
20

[Expected Approach] – Using Priority Queue – O(n^2 * log(k)) Time and O(k) Space

The idea is to use a max-heap to store and maintain the track of k smallest 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.

C++
// C++ program to find the Kth smallest element
#include <bits/stdc++.h>
using namespace std;

// Function to find the kth smallest 
// element in a sorted 2D matrix
int kthSmallest(vector<vector<int>>& matrix, int k) {
    int n = matrix.size();
    priority_queue<int> pq;

    // Traverse all elements in the matrix
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            int curr = matrix[i][j];

            // Push the current element into the max-heap
            pq.push(curr);

            // If the size of the max-heap exceeds k, 
            // remove the largest element
            if (pq.size() > k) {
                pq.pop();
            }
        }
    }

    // The top element of the max-heap 
    // is the kth smallest element
    return pq.top();
}

int main() {
    vector<vector<int>> matrix = 
                        {{10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {24, 29, 37, 48},
                        {32, 33, 39, 50 }};
    int k = 3;
    int result = kthSmallest(matrix, k);

    cout << result << endl;

    return 0;
}
Java
// Java program to find the Kth smallest element
import java.util.*;

class GfG {
    
    // Function to find the kth smallest 
    // element in a sorted 2D matrix
    static int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

        // Traverse all elements in the matrix
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                int curr = matrix[i][j];

                // Push the current element into the max-heap
                pq.offer(curr);

                // If the size of the max-heap exceeds k, 
                // remove the largest element
                if (pq.size() > k) {
                    pq.poll();
                }
            }
        }

        // The top element of the max-heap 
        // is the kth smallest element
        return pq.peek();
    }

    public static void main(String[] args) {
        int[][] matrix = 
                        {{10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {24, 29, 37, 48},
                        {32, 33, 39, 50}};
        int k = 3;
        int result = kthSmallest(matrix, k);

        System.out.println(result);
    }
}
Python
# Python program to find the Kth smallest element
import heapq

# Function to find the kth smallest 
# element in a sorted 2D matrix
def kthSmallest(matrix, k):
    n = len(matrix)
    pq = []

    # Traverse all elements in the matrix
    for i in range(n):
        for j in range(n):
            curr = matrix[i][j]

            # Push the current element into the max-heap
            heapq.heappush(pq, -curr)

            # If the size of the max-heap exceeds k, 
            # remove the largest element
            if len(pq) > k:
                heapq.heappop(pq)

    # The top element of the max-heap 
    # is the kth smallest element
    return -pq[0]

if __name__ == "__main__":
    matrix = [
                        [10, 20, 30, 40],
                        [15, 25, 35, 45],
                        [24, 29, 37, 48],
                        [32, 33, 39, 50]]
    k = 3
    result = kthSmallest(matrix, k)

    print(result)
C#
// C# program to find the Kth smallest element
using System;
using System.Collections.Generic;

class GfG {
    
    // Function to find the kth smallest 
    // element in a sorted 2D matrix
    static int kthSmallest(int[,] matrix, int k) {
        int n = matrix.GetLength(0);
        PriorityQueue<int> pq = 
        new PriorityQueue<int>
        (Comparer<int>.Create((a, b) => b.CompareTo(a)));

        // Traverse all elements in the matrix
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                int curr = matrix[i,j];

                // Push the current element into the max-heap
                pq.Enqueue(curr);

                // If the size of the max-heap exceeds k, 
                // remove the largest element
                if (pq.Count > k) {
                    pq.Dequeue();
                }
            }
        }

        // The top element of the max-heap 
        // is the kth smallest element
        return pq.Peek();
    }

    public static void Main(string[] args) {
        int[,] matrix = 
                        {{10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {24, 29, 37, 48},
                        {32, 33, 39, 50}};
        int k = 3;
        int result = kthSmallest(matrix, k);

        Console.WriteLine(result);
    }
}

public class PriorityQueue<T> {
    private List<T> data;
    private IComparer<T> comparer;

    public PriorityQueue(IComparer<T> comparer) {
        this.data = new List<T>();
        this.comparer = comparer;
    }

    public void Enqueue(T item) {
        data.Add(item);
        int ci = data.Count - 1;
        while (ci > 0) {
            int pi = (ci - 1) / 2;
            if (comparer.Compare(data[ci], data[pi]) >= 0) break;
            T tmp = data[ci]; data[ci] = data[pi]; data[pi] = tmp;
            ci = pi;
        }
    }

    public T Dequeue() {
        int li = data.Count - 1;
        T frontItem = data[0];
        data[0] = data[li];
        data.RemoveAt(li);

        --li;
        int pi = 0;
        while (true) {
            int ci = pi * 2 + 1;
            if (ci > li) break;
            int rc = ci + 1;
            if (rc <= li && comparer.Compare(data[rc], data[ci]) < 0)
                ci = rc;
            if (comparer.Compare(data[pi], data[ci]) <= 0) break;
            T tmp = data[pi]; data[pi] = data[ci]; data[ci] = tmp;
            pi = ci;
        }
        return frontItem;
    }

    public T Peek() {
        return data[0];
    }

    public int Count {
        get { return data.Count; }
    }
}
JavaScript
// JavaScript program to find the Kth smallest element

// MaxHeap implementation
class MaxHeap {
    constructor() {
        this.heap = [];
    }

    push(val) {
        this.heap.push(val);
        this.bubbleUp(this.heap.length - 1);
    }

    pop() {
        const max = this.heap[0];
        const end = this.heap.pop();
        if (this.heap.length > 0) {
            this.heap[0] = end;
            this.bubbleDown(0);
        }
        return max;
    }

    peek() {
        return this.heap[0];
    }

    size() {
        return this.heap.length;
    }

    bubbleUp(idx) {
        const element = this.heap[idx];
        while (idx > 0) {
            const parentIdx = Math.floor((idx - 1) / 2);
            const parent = this.heap[parentIdx];
            if (element <= parent) break;
            this.heap[idx] = parent;
            this.heap[parentIdx] = element;
            idx = parentIdx;
        }
    }

    bubbleDown(idx) {
        const length = this.heap.length;
        const element = this.heap[idx];
        while (true) {
            const leftChildIdx = 2 * idx + 1;
            const rightChildIdx = 2 * idx + 2;
            let leftChild, rightChild;
            let swap = null;

            if (leftChildIdx < length) {
                leftChild = this.heap[leftChildIdx];
                if (leftChild > element) {
                    swap = leftChildIdx;
                }
            }

            if (rightChildIdx < length) {
                rightChild = this.heap[rightChildIdx];
                if (
                    (swap === null && rightChild > element) ||
                    (swap !== null && rightChild > leftChild)
                ) {
                    swap = rightChildIdx;
                }
            }

            if (swap === null) break;
            this.heap[idx] = this.heap[swap];
            this.heap[swap] = element;
            idx = swap;
        }
    }
}

// Function to find the kth smallest 
// element in a sorted 2D matrix
function kthSmallest(matrix, k) {
    const n = matrix.length;
    const pq = new MaxHeap();

    // Traverse all elements in the matrix
    for (let i = 0; i < n; ++i) {
        for (let j = 0; j < n; ++j) {
            const curr = matrix[i][j];

            // Push the current element into the max-heap
            pq.push(curr);

            // If the size of the max-heap exceeds k, 
            // remove the largest element
            if (pq.size() > k) {
                pq.pop();
            }
        }
    }

    // The top element of the max-heap 
    // is the kth smallest element
    return pq.peek();
}

const matrix = 
                [[10, 20, 30, 40],
                [15, 25, 35, 45],
                [24, 29, 37, 48],
                [32, 33, 39, 50]];
const k = 3;
const result = kthSmallest(matrix, k);

console.log(result);

Output
20

[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.
C++
// C++ program to find the Kth smallest element
#include <bits/stdc++.h>
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
int kthSmallest(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() {
    vector<vector<int>> matrix = 
                        {{10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {24, 29, 37, 48},
                        {32, 33, 39, 50 }};
    int k = 3;
    int result = kthSmallest(matrix, k);

    cout << result << endl;

    return 0;
}
Java
// Java program to find the Kth smallest element
import java.util.*;

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.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
    static int kthSmallest(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) {
        int[][] matrix = 
                        {{10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {24, 29, 37, 48},
                        {32, 33, 39, 50}};
        int k = 3;
        int result = kthSmallest(matrix, k);

        System.out.println(result);
    }
}
Python
# Python program to find the Kth smallest element

# Function to count the number of elements less than or equal to x
def countSmallerEqual(matrix, x):
    n = len(matrix)
    count = 0
    row = 0
    col = 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

# Function to find the kth smallest 
# element in a sorted 2D matrix
def kthSmallest(matrix, k):
    n = len(matrix)
    low = matrix[0][0]
    high = matrix[n - 1][n - 1]
    ans = 0

    while low <= high:
        mid = low + (high - low) // 2
        
        # Count elements less than or equal to mid
        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

if __name__ == "__main__":
    matrix = [
                        [10, 20, 30, 40],
                        [15, 25, 35, 45],
                        [24, 29, 37, 48],
                        [32, 33, 39, 50]]
    k = 3
    result = kthSmallest(matrix, k)

    print(result)
C#
// C# program to find the Kth smallest element
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
    static int kthSmallest(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;
    }

    public static void Main(string[] args) {
        int[,] matrix = 
                        {{10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {24, 29, 37, 48},
                        {32, 33, 39, 50}};
        int k = 3;
        int result = kthSmallest(matrix, k);

        Console.WriteLine(result);
    }
}
JavaScript
// JavaScript program to find the Kth smallest element

// Function to count the number of elements less than or equal to x
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 to find the kth smallest 
// element in a sorted 2D matrix
function kthSmallest(matrix, k) {
    const n = matrix.length;
    let low = matrix[0][0];
    let high = matrix[n - 1][n - 1];
    let ans = 0;

    while (low <= high) {
        const mid = low + Math.floor((high - low) / 2);
        
        // Count elements less than or equal to mid
        const 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;
}

const matrix = 
                [[10, 20, 30, 40],
                [15, 25, 35, 45],
                [24, 29, 37, 48],
                [32, 33, 39, 50]];
const k = 3;
const result = kthSmallest(matrix, k);

console.log(result);

Output
20

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)


Next Article

Similar Reads