#1481. Least Number of Unique Integers after K Removals

ยท

1 min read

https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/description/?envType=daily-question&envId=2024-02-16



function findLeastNumOfUniqueInts(arr, k) {
    // Step 1: Count the frequency of each integer
    const freqMap = {};
    arr.forEach(num => {
        freqMap[num] = (freqMap[num] || 0) + 1;
    });

    // Step 2: Sort integers based on their frequencies in ascending order
    const sortedFreq = Object.values(freqMap).sort((a, b) => a - b);

    // Step 3: Start removing the integers with the lowest frequencies until K elements are removed
    let numUnique = Object.keys(freqMap).length;

    for (const freq of sortedFreq) {
        if (k >= freq) {
            k -= freq;
            numUnique--;
        } else {
            break;
        }
    }

    return numUnique;
}
ย