Show problems as
Classic problem #819EasyArrayHash TableStringCounting

Most Common Word

Real-world version: The Commonest Allowed Word
Tracked in this browser only
Read Most Common Word on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A notice is given as the string text, made of English letters in either case, spaces, and the marks '!', '?', "'", ',', ';' and '.'. A list of barred words is given as barred, all in lowercase.

Split the notice into words, where a word is a run of letters and everything else is a separator. Words are compared with case ignored.

Return, in lowercase, the word that appears most often among those not barred. Exactly one word appears most often, and at least one word is not barred.

Examples

Example 1

Input
text = "Cat cat CAT dog!", barred = ["dog"]
Output
"cat"

Case is ignored, so the three spellings of the same word count together as three, while the barred word is left out.

Example 2

Input
text = "a b a", barred = ["b"]
Output
"a"

The middle word is barred, leaving the other appearing twice.

Example 3

Input
text = "Tick tock tick tock tick", barred = []
Output
"tick"

The first word appears three times against the other's two, and since case is ignored the capitalised spelling counts with the rest.

Constraints

  • 1 <= text.length <= 1000
  • 0 <= barred.length <= 100
  • 1 <= barred[i].length <= 10
  • Every barred word is made of lowercase English letters.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def most_common_word(text: str, barred: list[str]) -> str:
Java
public String mostCommonWord(String text, String[] barred)