Top N Frequent Words in a File
Problem statement
You are given the contents of a text file as a string text and an integer n.
Extract every word from text. A word is a maximal nonempty sequence of ASCII letters. Convert words to lowercase, and treat every other character as a separator.
Return at most n distinct words ordered by decreasing frequency. When two words have the same frequency, order them lexicographically. If n exceeds the number of distinct words, return all distinct words. If the text contains no words, return an empty array.
Function
topNWords(text: String, n: int) → String[]Examples
Example 1
text = "Cat dog cat, DOG bird!"n = 2return = ["cat","dog"]cat and dog each appear twice. Their frequencies tie, so lexicographic order places cat first.
Example 2
text = "pear apple pear banana apple"n = 3return = ["apple","pear","banana"]apple and pear both appear twice, so the tie is resolved lexicographically. banana appears once.
Example 3
text = "One one two"n = 5return = ["one","two"]Only two distinct normalized words exist, so both are returned even though n = 5.
Constraints
0 <= text.length <= 2 * 10^5.1 <= n <= 10^5.- Every character in
textis an ASCII character.