Last active
March 11, 2024 22:37
-
-
Save bsturdivan/1c35f13ecaa54519c2b68c2067b0223b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function countOccurances(nums, k) { | |
let frquencyHash = {} | |
const frequencyArray = Array.from({ length: nums.length + 1 }, () => 0) | |
nums.forEach(num => { | |
frquencyHash[num] = (frquencyHash[num] || 0) + 1 | |
}) | |
for (const item in frquencyHash) { | |
frequencyArray[frquencyHash[item]] = ( | |
frequencyArray[frquencyHash[item]] || [] | |
).concat(item) | |
} | |
const sortedList = frequencyArray.sort((a,b) => b - a) | |
let mostFrequent = [] | |
let n = 1 | |
while (n <= k) { | |
mostFrequent = [...sortedList[n], ...mostFrequent] | |
n++ | |
} | |
return mostFrequent | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment