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]