Skip to content

Instantly share code, notes, and snippets.

@bsturdivan
Last active March 11, 2024 22:37
Show Gist options
  • Save bsturdivan/1c35f13ecaa54519c2b68c2067b0223b to your computer and use it in GitHub Desktop.
Save bsturdivan/1c35f13ecaa54519c2b68c2067b0223b to your computer and use it in GitHub Desktop.
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