File: counting-words-with-a-given-prefix/solution.py

Date: 2026-06-06

Time: 16:08

counting-words-with-a-given-prefix/solution.py

Purpose

This file solves LeetCode 2185 — Counting Words With a Given Prefix. It provides the single function the project needs: given a list of words and a prefix string, count how many words start with that prefix. It's a straightforward string-matching problem categorized as Easy.

Key Components

countprefixes(words, pref) -> int — The sole public function. Takes a list of strings and a prefix, returns the count of words that begin with pref. The function name deviates from LeetCode's canonical prefixCount — this repo uses snakecase throughout.

The implementation is a one-liner: sum(w.startswith(pref) for w in words). This exploits Python's truthy coercion — str.startswith() returns bool, and sum() treats True as 1. The generator expression avoids allocating an intermediate list.

Patterns

Dependencies

Imports: typing.List — used only for the type annotation. On Python 3.9+ this could be replaced with list[str], but the repo targets broader compatibility.

Imported by: The "Imported By" list in the prompt is misleading — those are test files across the entire repo that import from their *own* solution.py, not from this file specifically. The actual dependent is counting-words-with-a-given-prefix/test_solution.py.

Flow

1. Caller passes words (list of strings) and pref (string).

2. Generator iterates over words, calling w.startswith(pref) on each.

3. sum() consumes the generator, accumulating True values as 1.

4. Returns the integer count.

No early termination — every word is checked. This is fine given LeetCode's constraints (n ≤ 100, word length ≤ 100).

Invariants

Error Handling

None. The function trusts its inputs per LeetCode's contract. An empty words list returns 0 naturally (sum of empty generator). A pref longer than any word simply yields all False from startswith, returning 0.

Topics to Explore

Beliefs