JavaScript Program to Find kth Largest/Smallest Element in an Array
JavaScript allows us to find kth largest/smallest element in an array. We are given an array containing some elements, we have to find kth smallest/largest element from the array where k is a number greater than zero and less than equal to the total number of elements present in the array.
There are several ways to find the kth largest/smallest element in an array using JavaScript which are as follows:
Using the Brute force approach
We are going to discuss how to find kth We will arrange the elements of the given array in a sorted manner. We will assume that the array is present in zero-based indexing order. If n is the size of the array then we return (n-k) as the kth largest element of the array and (k-1) as the smallest element of the array (because the array is 0-base indexed).
Example: JavaScript code, encapsulated in a class, efficiently sorts an array and prints the kth largest and smallest elements, providing a concise solution for such queries.
class Solution {
kthLargestAndSmallest(arr, k) {
arr.sort((a, b) =& gt; a - b);
const n = arr.length;
console.log(`kth Largest element in the array is ${arr[n - k]}`);
console.log(`kth Smallest element in the array is ${arr[k - 1]}`);
}
}
const obj = new Solution();
const arr = [6, 4, 3, 7, 8, 2];
obj.kthLargestAndSmallest(arr, 4);
Output
kth Largest element in the array is 4 kth Smallest element in the array is 6
Time Complexity : O(nlogn) , we are using inbuilt sort function.
Space Complexity : O(1) , as it is taking constant time
Using heaps
To reduce the time complexity of above brute force approach we will use heap max-heap/mean-heap to return the kth largest/smallest element present in the array. Max-heap is used to find kth largest element of array because it stores elements in descending order and . For kth largest element we will push elements in max-heap and then pop elements till k-1 elements and then return top element of max-heap as kth largest element of the array. Similarly, for kth smallest element we will push elements in min-heap and then pop elements till k-1 elements and then return top element of min-heap as kth smallest element of the array. There is no inbuilt function for implementing max/min heap in JavaScript. So we have to first implement priorityQueue for using heap.
Example: This JavaScript code, utilizing priority queues, efficiently finds the kth largest and smallest elements in an array, offering a structured and scalable solution for such computations.
class Solution {
kthLargestElement(arr, k) {
const pq = new PriorityQueue();
for (let i = 0; i & lt; arr.length; i++) {
pq.push(arr[i]);
}
let s = k - 1;
while (s & gt; 0) {
pq.pop();
s--;
}
console.log(`Kth Largest element of the array is ${pq.top()}`);
}
kthSmallestElement(arr, k) {
const pq = new PriorityQueueMin();
for (let i = 0; i & lt; arr.length; i++) {
pq.push(arr[i]);
}
let s = k - 1;
while (s & gt; 0) {
pq.pop();
s--;
}
console.log(`Kth Smallest element of the array is ${pq.top()}`);
}
}
class PriorityQueue {
constructor() {
this.data = [];
}
push(value) {
this.data.push(value);
}
pop() {
this.data.sort((a, b) =& gt; b - a);
this.data.pop();
}
top() {
this.data.sort((a, b) =& gt; b - a);
return this.data[0];
}
}
class PriorityQueueMin {
constructor() {
this.data = [];
}
push(value) {
this.data.push(value);
}
pop() {
this.data.sort((a, b) =& gt; a - b);
this.data.pop();
}
top() {
this.data.sort((a, b) =& gt; a - b);
return this.data[0];
}
}
const obj = new Solution();
const arr = [6, 5, 3, 8, 9];
obj.kthLargestElement(arr, 4);
obj.kthSmallestElement(arr, 4);
Output
Kth Largest element of the array is 9 Kth Smallest element of the array is 3
Time Complexity : O(k+(n-k)*log(k)) , we are using heap implementation.
Space Complexity : O(k)
Using quickselect algorithm
The Quickselect algorithm finds the kth largest or smallest element efficiently by recursively partitioning the array around a pivot, narrowing down the search space. It achieves an average time complexity of O(n), making it faster than brute force or heap methods.
Example:
function quickselect(arr, k, left = 0, right = arr.length - 1) {
if (left === right) {
return arr[left];
}
let pivotIndex = partition(arr, left, right);
if (k === pivotIndex) {
return arr[k];
} else if (k < pivotIndex) {
return quickselect(arr, k, left, pivotIndex - 1);
} else {
return quickselect(arr, k, pivotIndex + 1, right);
}
}
function partition(arr, left, right) {
let pivot = arr[right];
let i = left;
for (let j = left; j < right; j++) {
if (arr[j] <= pivot) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
}
}
[arr[i], arr[right]] = [arr[right], arr[i]];
return i;
}
function findKthLargest(arr, k) {
return quickselect(arr, arr.length - k);
}
function findKthSmallest(arr, k) {
return quickselect(arr, k - 1);
}
const arr = [3, 2, 1, 5, 6, 4];
const k = 2;
console.log(findKthLargest(arr, k));
console.log(findKthSmallest(arr, k));
Output
5 2