Problem 214658 · easy · Level 02 Linear Data Structures

Most Frequent Word

strings · counting · dicts

Write most_common_word(text) that returns the word occurring most often in text. A word is a maximal run of letters; every other character (spaces, digits, punctuation, apostrophes) separates words. Comparison is case-insensitive and the result is returned in lowercase. If several words tie, return the alphabetically smallest. Return "" if there are no words.

Examples

Input:  text = "The cat and the hat. THE end!"
Output: "the"

Input:  text = "a b b a"
Output: "a"
Explanation: "a" and "b" both appear twice; "a" comes first alphabetically.

Input:  text = ""
Output: ""

Constraints

  • 0 <= len(text) <= 10**5, printable ASCII
  • Target: O(n) time plus sorting the distinct words

Goals

  • Tokenise text into words without regex
  • Normalise case before counting
  • Break ties deterministically
Starting Python…