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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read