JavaScript Program to Find k Most Occurrences in the Given Array
Last Updated :
16 Jul, 2024
K most occurrences in an array refer to finding the K unique elements that appear the most frequently within the given array, where K is a specified integer. These are the elements with the highest frequencies in the array.
Example:
Input: arr[] = {3, 1, 4, 4, 5, 2, 6, 1}, K = 2
Output: 4 1
Explanation:
Frequency of 4 = 2, Frequency of 1 = 2
These two have the maximum frequency and 4 is larger than 1.
refer
Input: arr[] = {7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9}, K = 4
Output: 5 11 7 10
Explanation:
Frequency of 5 = 3, Frequency of 11 = 2, Frequency of 7 = 2, Frequency of 10 = 1
These four have the maximum frequency and 5 is largest among rest.
Approach 1: Using map() method
In This approach we are using the map() method to count the occurrences of elements in an array, creating a frequency map. It then converts this map into an array of [element, frequency] pairs, sorts them by frequency in descending order, and finally, extracts the top k elements, providing an efficient solution for finding k most occurring elements.
Syntax:
map((element) => { /* … */ })
Example: Below is the implementation of the above approach.
JavaScript
function frequentElements(arr, k) {
const frequencyMap = new Map();
// Count the occurrences of
// each element in the array
for (let i = 0; i < arr.length; i++) {
const num = arr[i];
frequencyMap.has(num)
? frequencyMap.
set(num, frequencyMap.get(num) + 1)
: frequencyMap.set(num, 1);
}
// Sort the entries in the frequency
// map by frequency in descending order
const sortedEntries =
[...frequencyMap.entries()]
.sort((a, b) => b[1] - a[1]);
const result = [];
// Extract the first k elements
// from the sorted entries
for (let i = 0; i < k &&
i < sortedEntries.length; i++) {
result.push(sortedEntries[i][0]);
}
return result;
}
const arr = [3, 1, 4, 4, 5, 2, 6, 1];
const k = 2;
const kMostFrequent = frequentElements(arr, k);
console.log(...kMostFrequent);
Approach 2: Using reduce() with sort() method
In This approach uses the reduce() method to create a frequency map of elements in the array, followed by sorting the map entries using sort(). Finally, it extracts the top k elements from the sorted entries to find the k most frequent elements.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue )
Example: Below is the implementation of the above approach.
JavaScript
function frequentElements(arr, k) {
const frequencyMap =
arr.reduce((map, num) => {
map.set(num, (map.get(num) || 0) + 1);
return map;
}, new Map());
// Sort the entries in the frequency
// map by frequency in descending order
const sortedEntries =
[...frequencyMap.entries()]
.sort((a, b) => b[1] - a[1]);
const result = [];
for (const [element, _] of
sortedEntries.slice(0, k)) {
result.push(element);
}
return result;
}
const arr = [3, 1, 4, 4, 5, 2, 6, 1];
const k = 2;
const kMostFrequent =
frequentElements(arr, k);
console.log(...kMostFrequent);
Approach 3: Using a Min-Heap (Priority Queue)
In this approach, we use a min-heap to efficiently find the K most frequent elements in the array. A min-heap allows us to keep track of the top K elements with the highest frequencies while ensuring that the heap size never exceeds K. This method is particularly efficient when K is much smaller than the number of unique elements in the array.
Example:
JavaScript
function topKFrequentElements(arr, K) {
// Step 1: Create a frequency map
const freqMap = new Map();
for (let num of arr) {
freqMap.set(num, (freqMap.get(num) || 0) + 1);
}
// Step 2: Use a min-heap to track top K elements
const minHeap = new MinHeap();
for (let [num, freq] of freqMap) {
minHeap.insert([freq, num]);
if (minHeap.size() > K) {
minHeap.remove();
}
}
// Step 3: Extract elements from the min-heap
const result = [];
while (minHeap.size() > 0) {
result.push(minHeap.remove()[1]);
}
// The result array will contain the K most frequent elements
return result.reverse(); // To get the elements in descending order of frequency
}
// MinHeap class implementation
class MinHeap {
constructor() {
this.heap = [];
}
size() {
return this.heap.length;
}
insert(value) {
this.heap.push(value);
this._heapifyUp();
}
remove() {
const root = this.heap[0];
const end = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = end;
this._heapifyDown();
}
return root;
}
_heapifyUp() {
let index = this.heap.length - 1;
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if (this.heap[index][0] >= this.heap[parentIndex][0]) break;
[this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]];
index = parentIndex;
}
}
_heapifyDown() {
let index = 0;
const length = this.heap.length;
const element = this.heap[0];
while (true) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let leftChild, rightChild;
let swap = null;
if (leftChildIndex < length) {
leftChild = this.heap[leftChildIndex];
if (leftChild[0] < element[0]) {
swap = leftChildIndex;
}
}
if (rightChildIndex < length) {
rightChild = this.heap[rightChildIndex];
if ((swap === null && rightChild[0] < element[0]) || (swap !== null && rightChild[0] < leftChild[0])) {
swap = rightChildIndex;
}
}
if (swap === null) break;
[this.heap[index], this.heap[swap]] = [this.heap[swap], this.heap[index]];
index = swap;
}
}
}
// Examples
const arr1 = [3, 1, 4, 4, 5, 2, 6, 1];
const K1 = 2;
console.log(topKFrequentElements(arr1, K1)); // Output: [4, 1]
const arr2 = [7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9];
const K2 = 4;
console.log(topKFrequentElements(arr2, K2)); // Output: [5, 11, 7, 10]
Output[ 1, 4 ]
[ 5, 11, 7, 9 ]
Approach 4: Using JavaScript's Map Object and Sorting
In this approach, we use JavaScript's Map object to create a frequency map of the elements in the array. We then convert this map into an array of [element, frequency] pairs, sort them based on frequency in descending order, and extract the top K elements. This approach is straightforward and leverages JavaScript's built-in data structures for efficient computation.
Example:
JavaScript
function kMostFrequentElements(arr, K) {
const frequencyMap = new Map();
arr.forEach(element => {
frequencyMap.set(element, (frequencyMap.get(element) || 0) + 1);
});
const sortedFrequencyArray = [...frequencyMap.entries()].sort((a, b) => b[1] - a[1]);
return sortedFrequencyArray.slice(0, K).map(entry => entry[0]);
}
let arr1 = [3, 1, 4, 4, 5, 2, 6, 1];
let K1 = 2;
console.log(kMostFrequentElements(arr1, K1));
let arr2 = [7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9];
let K2 = 4;
console.log(kMostFrequentElements(arr2, K2));
Output[ 1, 4 ]
[ 5, 7, 11, 10 ]
Similar Reads
JavaScript Program to Find k Most Frequent Elements in Array In this article, we are given an input array with the elements and k value. Our task is to find out the most frequent elements in the array as per the k value using JavaScript. Below we have added the example for better understanding. Example: Input: array = [7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9] , K
3 min read
JavaScript Program to Find all Elements that Appear More than n/k Times We are given an array that has n number of elements and an integer k, we have to return all the elements which will appear more than n/k times in the array using JavaScript. Examples:Input: arr = {4, 2, 4, 1, 4, 5, 5, 5}, k=3Output: {4 , 5}Explanation: The elements {4, 5} appears more than n/k i.e.
3 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
Java Program to Print the kth Element in the Array We need to print the element at the kth position in the given array. So we start the program by taking input from the user about the size of an array and then all the elements of that array. Now by entering the position k at which you want to print the element from the array, the program will print
2 min read
Find the most frequent element K positions apart from X in given Array Given an array nums[], and integer K and X, the task is to find the most frequent element K positions away from X in the given array. Examples: Input: nums = [1, 100, 200, 1, 100], K = 1, X = 1Output: 100Explanation: Elements 1 position apart from 1 is only 100.So the answer is 100. Input: nums = [2
6 min read