File: most-common-word/solution.py

Date: 2026-06-06

Time: 18:07

most-common-word/solution.py

Purpose

Solves LeetCode 819: Most Common Word. Given a paragraph string and a list of banned words, it finds the most frequently occurring word that isn't banned. This is a string-processing + frequency-counting problem.

Key Components

Solution.mostCommonWord(paragraph, banned) -> str — The single method. Contract:

Patterns

The solution follows a pipeline transformation pattern common across this repo's solutions:

1. Normalizeparagraph.lower() flattens case.

2. Tokenizere.findall(r'[a-z]+', ...) extracts word tokens, implicitly stripping all punctuation and spaces. This is more robust than splitting on whitespace because it handles adjacent punctuation like "ball,""ball".

3. Filter — Generator expression excludes banned words using a set lookup.

4. AggregateCounter tallies frequencies; most_common(1) extracts the winner.

The banned list is converted to a set for O(1) membership testing — a standard idiom when you need repeated in checks against a fixed collection.

Dependencies

Flow


paragraph string
  → .lower()                          # case-normalize
  → re.findall(r'[a-z]+', ...)       # tokenize into word list
  → filter out banned (via set)       # generator, lazy
  → Counter(...)                      # count frequencies
  → .most_common(1)[0][0]            # extract top word

Everything happens in four lines. The generator expression (w for w in words if w not in banned_set) is lazy — it doesn't materialize a filtered list, feeding tokens directly into Counter.

Invariants

Error Handling

None. If the paragraph contains no valid non-banned words, counts.most_common(1) returns an empty list and [0][0] raises IndexError. This is acceptable for a LeetCode solution where the problem guarantees valid input.

Topics to Explore

Beliefs