File: count-asterisks/solution.py

Date: 2026-06-06

Time: 15:54

count-asterisks/solution.py

Purpose

This file solves LeetCode 2315: Count Asterisks. It owns the single responsibility of counting * characters in a string while ignoring any * that falls between a matched pair of | delimiters. It's the canonical solution module for this problem in the leetcode-implementations repo.

Key Components

countstarsexceptbetweenpair(s: str) -> int — The sole function. Its contract:

Patterns

Toggle-flag state machine — The function uses a boolean inside as a two-state automaton. Each | flips the state. This is the standard idiom for "skip content between matched delimiters" when delimiters don't nest and always come in pairs. It avoids the overhead of splitting or regex and processes the string in a single pass.

The approach is O(n) time, O(1) space — no auxiliary data structures, no string slicing.

Dependencies

Imports: None. The function uses only Python builtins.

Imported by: The "Imported By" list in the prompt is misleading — those hundreds of test files are unrelated problems. The actual consumer is count-asterisks/test_solution.py. The other test files likely share a common test harness or conftest that imports broadly, not this function specifically.

Flow

1. Initialize count = 0 (accumulator) and inside = False (state flag).

2. Iterate character-by-character over s.

3. On |: toggle inside. This pairs the 1st | with the 2nd, the 3rd with the 4th, etc.

4. On * when inside is False: increment count. Asterisks inside paired bars are silently skipped.

5. All other characters (lowercase letters, * when inside): ignored.

6. Return the final count.

For input "l|*e*et|c**o|*de|":

Invariants

Error Handling

None. The function assumes valid input per the problem constraints. An empty string returns 0 (the loop simply doesn't execute). No exceptions are raised or caught.

Topics to Explore

Beliefs