JavaScript Program to Find kth Largest/Smallest Element in an Array
Last Updated :
03 Jul, 2024
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.
JavaScript
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);
Outputkth 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.
JavaScript
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);
OutputKth 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:
JavaScript
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));
Similar Reads
JavaScript Program to Find Largest Element in an Array In this article, we are going to learn about the largest element in an array in JavaScript. The largest element in an array refers to the value that holds the greatest numerical or lexicographic (string) order among all elements present in the array. Example: Input : [10, 15, 38, 20, 13];Output: 38H
3 min read
JavaScript Program to Find Kth Smallest/Largest Element in a Sorted Matrix 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 40Explanation: The 3rd smallest element is 20 The
3 min read
JavaScript Program to find the Nth smallest/largest element from an unsorted Array In this article, we will see how to find Nth largest and smallest element from an unsorted array. The Nth smallest/largest element from an unsorted array refers to the element that ranks at the Nth position when the array is sorted either in ascending (smallest) or descending (largest) order. It rep
4 min read
Javascript Program to Find k maximum elements of array in original order Given an array arr[] and an integer k, we need to print k maximum elements of given array. The elements should printed in the order of the input.Note: k is always less than or equal to n.Examples: Input : arr[] = {10 50 30 60 15} k = 2 Output : 50 60 The top 2 elements are printed as per their appea
3 min read
How to get largest and smallest number in an Array? Given an array arr[] of length N, The task is to find the maximum and the minimum number in the array. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: Maximum is: 5Minimum is: 1Explanation: The maximum of the array is 5 and the minimum of the array is 1. Input: arr[] = {5, 3, 7, 4, 2}Output: Maximum
15 min read
PHP program to find the maximum and the minimum in array Finding the maximum and minimum in an array involves determining the largest and smallest values within a given set of numbers. This task is crucial for analyzing data, identifying trends, or filtering outliers. Various methods, from simple traversal to optimized algorithms, can achieve this.Example
7 min read
Javascript Program for Maximum and Minimum in a square matrix. Given a square matrix of order n*n, find the maximum and minimum from the matrix given. Examples: Input : arr[][] = {5, 4, 9, 2, 0, 6, 3, 1, 8}; Output : Maximum = 9, Minimum = 0 Input : arr[][] = {-5, 3, 2, 4}; Output : Maximum = 4, Minimum = -5 Naive Method : We find maximum and minimum of matrix
3 min read
Javascript Program For Rearranging An Array In Maximum Minimum Form - Set 2 (O(1) extra space) Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples:Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Input: arr[] = {1, 2, 3, 4
5 min read
Kth Smallest Number in Multiplication Table Given three integers m, n, and k. Consider a grid of m * n, where mat[i][j] = i*j (1 based indexing). The task is to return the k'th smallest element in the m*n multiplication table.Examples: Input: m = 3, n = 3, k = 5Output: 3Explanation:The 5th smallest element is 3. Input: m = 2, n = 3, k = 6Outp
13 min read
Java Program to Print the Smallest Element in an Array Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read