Oscar Health | OA | Find K most frequent words
Anonymous User
651

Given a sentence and integer K find the count of most frequent K words in it.

If K is greater than all unique words in sentence return all words.
If K ==0 return empty list

eg. Once thrice twice thrice thrice thrice , K=2

Ans: Thrice, Twice

K = 2

Follow Up:
If two words have same frequency then sort them alphabetically.

Solution:
Use a hashmap to store count and word
User Priority Queue of Pair<String,Integer> with a comparator and insert all elements in PQ;
Add elements from top of PQ until k>0 && !pq.isEmpty() {case where K is greater than unique words count}

Comments (1)