Open In App

JavaScript Program to Find Kth Smallest/Largest Element in a Sorted Matrix

Last Updated : 08 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an n x n matrix, where every row and column is sorted in non-decreasing order. Find the kth smallest/largest element in the given 2D array.

Examples:

Input:k = 3 and array =
10, 20, 30, 40
15, 25, 35, 45
24, 29, 37, 48
32, 33, 39, 50
Output: 20
40
Explanation: The 3rd smallest element is 20
The 3rd largest element is 45

Input:k = 7 and array =
10, 20, 30, 40
15, 25, 35, 45
24, 29, 37, 48
32, 33, 39, 50
Output: 30
35
Explanation: The 7th smallest element is 30
The 7th largest element is 35

Below are the approaches to finding kth smallest/largest element in a sorted matrix.

Using a flat array and Sorting

In this approach, we are using a flat array obtained from the matrix to find the kth smallest and kth largest elements by sorting them in ascending order and accessing the desired positions directly.

Example: The below example uses a flat array and Sorting to find kth smallest/largest element in a sorted matrix

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

let flatArray = matrix.flat().sort((a, b) => a - b);
let small = flatArray[k - 1];
let large = flatArray[flatArray.length - k];
console.log("Kth Smallest:", small);
console.log("Kth Largest:", large);

Output
Kth Smallest: 20
Kth Largest: 45

Time Complexity: O(nlogn) time, where n is the total number of elements in the matrix.

Space Complexity: O(n)

Using Min-Heap

In this approach, we create separate min and max heaps by flattening the matrix, sorting each heap, and then directly accessing the kth smallest and kth largest elements from the heaps.

Example: The below example uses Min-Heap to find kth smallest/largest element in a sorted matrix

JavaScript
let k = 3;
let matrix = [
    [10, 20, 30, 40],
    [15, 25, 35, 45],
    [24, 29, 37, 48],
    [32, 33, 39, 50]
];
let minHeap = [];
let maxHeap = [];
for (let row of matrix) {
    minHeap
        .push(...row);
    maxHeap
        .push(...row);
}
minHeap
    .sort((a, b) => a - b);
maxHeap
    .sort((a, b) => b - a);
let small = minHeap[k - 1];
let large = maxHeap[k - 1];
console.log("Kth Smallest:", small);
console.log("Kth Largest:", large);

Output
Kth Smallest: 20
Kth Largest: 45

Time Complexity: O(nlogk) time, where n is the total number of elements in the matrix and k is the value of k.

Space Complexity: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads