File: split-a-string-in-balanced-strings/solution.py

Date: 2026-06-06

Time: 19:14

Purpose

This file implements LeetCode problem 1221 — Split a String in Balanced Strings. It solves the problem of finding the maximum number of balanced substrings (substrings with equal counts of 'L' and 'R') that a balanced string can be split into. The file is self-contained: it defines the solution function and its unit tests in one module.

Key Components

findspecialinteger(s: str) -> int

Despite its misleading name (likely a copy-paste artifact from a template — the function has nothing to do with "special integers"), this is the core solver. Its contract:

TestFindSpecialInteger

Six test cases covering the LeetCode examples plus edge cases: minimal input ("RL"), alternating characters, and nested structure ("RRLLRRLL").

Patterns

Greedy counter pattern. The solution uses a single integer balance as a stand-in for tracking 'R' vs 'L' counts. 'R' increments, 'L' decrements. When balance hits zero, both characters have appeared equally — that's a split point. This is the canonical O(n) greedy approach for this problem; no stack or auxiliary data structure needed.

Self-contained test module. The file bundles unittest.TestCase alongside the solution, runnable via python -m unittest or python solution.py directly through the if _name_ guard.

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The testsolution.py in this same directory, plus hundreds of testsolution.py files across other problem directories. This is almost certainly a dependency-graph artifact — those other test files likely import from their *own* solution.py, not this one. The Imported By list reflects a tool that resolved import solution ambiguously across the flat directory structure.

Flow

1. Initialize balance = 0 and result = 0.

2. Iterate character by character through s.

3. For each 'R', add 1 to balance; for each 'L', subtract 1.

4. Whenever balance == 0, increment result — we've found a balanced substring.

5. Return result.

For "RLRRLLRLRL": the balance trace is [1,0,1,2,1,0,1,0,1,0], hitting zero at indices 1, 5, 7, 9 → returns 4.

Invariants

Error Handling

None. The function trusts its input — no validation that s contains only 'L'/'R', no check that the string is balanced. Consistent with LeetCode solution conventions where inputs are guaranteed by the problem constraints.

Topics to Explore

Beliefs