LeetCode: Top K Frequent Words Solution

Hash and sort

Approach

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

Original problem

Map object (MDN doc)

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

Next Post

LeetCode: Combination Sum II

Backtracking with duplication check

Previous Post

HoningJS

Search Posts