File: count-prefixes-of-a-given-string/solution.py

Date: 2026-06-06

Time: 16:03

Purpose

This file is a self-contained solution to LeetCode 2255: Count Prefixes of a Given String. It owns both the algorithm implementation and its test suite, following the repo-wide pattern of one directory per problem with solution.py containing everything needed to verify correctness.

Key Components

Solution.countPrefixes(words, s) -> int

The core algorithm. Given a list of strings words and a target string s, it returns how many elements of words are prefixes of s. The implementation is a single generator expression: sum(1 for w in words if s.startswith(w)). This delegates the prefix-matching logic entirely to Python's built-in str.startswith, which handles edge cases like empty strings and length mismatches internally.

Contract: accepts any List[str] and a str; returns a non-negative integer. Duplicates in words are counted independently (tested explicitly in test_duplicates).

TestCountPrefixes

Eight test methods covering: LeetCode's provided examples, no-match case, word longer than s, exact equality, single character, all matching, and duplicate words. The test class uses setUp to instantiate Solution once per test.

Patterns

Dependencies

Imports: List from typing (for type annotation), unittest (for test harness). No project-internal imports.

Imported by: The "Imported By" list in the prompt is misleading — those are test files from *other* problem directories, not actual importers of this module. They likely share test infrastructure or were auto-generated from the same template. This file does not export anything consumed by other solutions.

Flow

1. countPrefixes iterates over words once.

2. For each word w, s.startswith(w) checks whether s[:len(w)] == w in O(len(w)) time.

3. Matching words contribute 1 to the sum; non-matching contribute 0.

4. Total time: O(sum of lengths of all words), bounded by O(n * len(s)).

Invariants

Error Handling

None. The function assumes valid inputs per LeetCode constraints (non-empty list, lowercase English letters). str.startswith handles empty-string edge cases gracefully (returns True), but no tests cover that scenario.

Topics to Explore

Beliefs