LeetCode: Top K Frequent Words Solution
Hash and sortApproach
Transform the words array to array of
[word, occurence]
Sort the array by multiple criteria, desc by
occurence
, asc by word
(lexicographical order)Implementation
1var topKFrequent = function (words, k) {2 return Array.from(3 words.reduce((acc, el) => acc.set(el, (acc.get(el) || 0) + 1), new Map())4 )5 .sort(6 ([wordA, occurenceA], [wordB, occurenceB]) =>7 occurenceB - occurenceA || wordA.localeCompare(wordB)8 )9 .slice(0, k)10 .map(([word]) => word)11}
References
Similar problems
Top K Frequent Elements
K Closest Points to Origin
Sort Features by Popularity
Sender With Largest Word Count
Maximum Number of Pairs in Array
Comments
Loading comments...
Tags
leetcode
sorting
hash table
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.