class PriorityQueue {
constructor(compareFunc) {
this
.heap = [];
this
.compare = compareFunc || ((a, b) => a - b);
}
enqueue(val) {
this
.heap.push(val);
this
.bubbleUp();
}
dequeue() {
if
(
this
.isEmpty()) {
throw
new
Error(
'Queue is empty'
);
}
const max =
this
.peek();
const last =
this
.heap.pop();
if
(
this
.size() > 0) {
this
.heap[0] = last;
this
.bubbleDown();
}
return
max;
}
peek() {
if
(
this
.isEmpty()) {
throw
new
Error(
'Queue is empty'
);
}
return
this
.heap[0];
}
size() {
return
this
.heap.length;
}
isEmpty() {
return
this
.size() === 0;
}
bubbleUp() {
let index =
this
.size() - 1;
while
(index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if
(
this
.compare(
this
.heap[index],
this
.heap[parentIndex]) >= 0) {
break
;
}
[
this
.heap[parentIndex],
this
.heap[index]] = [
this
.heap[index],
this
.heap[parentIndex],
];
index = parentIndex;
}
}
bubbleDown() {
let index = 0;
const lastIndex =
this
.size() - 1;
while
(
true
) {
const leftChildIndex = index * 2 + 1;
const rightChildIndex = index * 2 + 2;
let minChildIndex =
null
;
if
(leftChildIndex <= lastIndex) {
minChildIndex = leftChildIndex;
}
if
(rightChildIndex <= lastIndex &&
this
.compare(
this
.heap[rightChildIndex],
this
.heap[leftChildIndex]) < 0) {
minChildIndex = rightChildIndex;
}
if
(minChildIndex ===
null
||
this
.compare(
this
.heap[index],
this
.heap[minChildIndex]) <= 0) {
break
;
}
[
this
.heap[index],
this
.heap[minChildIndex]] = [
this
.heap[minChildIndex],
this
.heap[index],
];
index = minChildIndex;
}
}
}
function
distinctIds(arr, n, k) {
let mp =
new
Map();
for
(let i = 0; i < n; i++) {
mp.set(arr[i], (mp.get(arr[i]) || 0) + 1);
}
let pq =
new
PriorityQueue((a, b) => a - b);
for
(let [key, val] of mp.entries()) {
pq.enqueue(val);
}
while
(k > 0 && !pq.isEmpty()) {
k -= pq.dequeue();
}
return
pq.size();
}
const arr = [2, 3, 1, 2, 3, 3];
const n = arr.length;
const k = 3;
console.log(distinctIds(arr, n, k));