File: check-if-all-as-appears-before-all-bs/solution.py

Date: 2026-06-06

Time: 15:36

check-if-all-as-appears-before-all-bs/solution.py

Purpose

This file solves LeetCode 2124: Check if All A's Appears Before All B's. It owns the single responsibility of determining whether a string of 'a's and 'b's has all 'a's preceding all 'b's — i.e., the string matches the pattern a*b*.

Key Components

Solution.checkIfAllAsAppearsBeforeAllBs(self, s: str) -> bool — The only method. Takes a string consisting solely of 'a' and 'b' characters and returns True if no 'a' appears after any 'b'.

Patterns

The solution uses substring negation rather than iteration: instead of scanning characters and tracking state transitions, it checks for the absence of the forbidden substring "ba". This is the idiomatic Python approach — delegating the scan to CPython's optimized C-level _contains_ implementation.

The insight is that "ba" exists in the string if and only if some 'a' appears after some 'b'. The problem reduces to a single membership test.

Dependencies

Imports: None. The solution is self-contained with no stdlib or third-party imports.

Imported by: The test_solution.py in the same directory imports this Solution class. The massive "Imported By" list in the prompt is misleading — those are unrelated test files across the repo that import their own local Solution classes, not this one.

Flow

1. Python's not in operator calls str._contains_, which runs a substring search (a variant of the Boyer-Moore or two-way algorithm in CPython).

2. If "ba" is found anywhere in s, the method returns False.

3. If "ba" is not found, it returns True.

No loops, no state, no intermediate data structures. The entire function is a single expression.

Invariants

Error Handling

None. The method cannot raise under valid inputs. For empty strings, "ba" not in "" returns True, which is correct (vacuously, all a's appear before all b's).