Most Common Words
EasyWe want to find the most frequently used words in a long string of text. Write a function most_common_words(text) that returns an array containing words with their frequencies, sorted from most common to least common, with ties broken by alphabetic order.
For greater accuracy, your solution should ignore punctuation and capitalization.
Pythondef most_common_words(text):
# Your code here
Examples
For example, given the string
Pythontext = 'It was the best of times, it was the worst of times.'
then most_common_words(text) should return
Our solution processes the input text by making it lowercase, removing punctuation, splitting the words by whitespace, and then building a frequency dictionary. Finally, it returns the sorted entries, first sorting by alphabetical order and then by frequency (Note: this assumes the use of a stable sorting algorithm, which Python and JavaScript use by default).
We provide two potential implementations. The first uses the language's built-in regular expression library and string splitting, making it more readable and easier to implement. The second solution is more performant as it sanitizes and splits the input text in a single pass. Both implementations have similar time complexity because the bottleneck is the sorting step, which is O(n log n).
Solution 1: Using Regular Expressions and Built-in Split Method
Solution 2: Sanitizing and Splitting in One Pass
Time Complexity: Both solutions have a time complexity dominated by the sorting step, which is O(n log n), where n is the number of unique words.
Space Complexity: Both solutions use O(n) space for the frequency dictionary and the sorted list of words, where n is the number of unique words in the text.
Interview experiences
2 sharedRelated courses



