kth frequent element

by Krishna Ananthi

JavaScript

var topKFrequent = function (nums, k) { //bucket sorting
  let count = {}, res = [];
    let freq = Array.from({ length: nums.length + 1 }, () => []);

    for (let n of nums) {
        count[n] = (count[n] || 0) + 1;
    }

    for (let n in count) {
        freq[count[n]].push(parseInt(n));
    }
console.log(freq, freq.length)
    for (let i = freq.length-1; i > 0; i--) {
        for (const n of freq[i]) {
            res.push(n)
            if (res.length == k)
                return res;
        }
    }
    
}

console.log(topKFrequent([1, 2], 2))