File: consecutive-characters/solution.py

Date: 2026-06-06

Time: 15:49

consecutive-characters/solution.py

Purpose

This file solves LeetCode 1446 — Consecutive Characters. It computes the power of a string, defined as the length of the longest substring consisting of a single repeated character. The file owns exactly one responsibility: implementing the Solution.maxPower method for submission to LeetCode's judge.

Key Components

Solution.maxPower(self, s: str) -> int — The sole public method. Takes a non-empty string s and returns the length of its longest run of identical consecutive characters.

Patterns

Single-pass linear scan. The algorithm walks the string once from index 1, comparing each character to its predecessor. This is the canonical "current vs. previous" pattern for run-length problems — no auxiliary data structures, no groupby, no regex.

Eager max update. Rather than computing maxcount = max(maxcount, count) after the loop or at every step unconditionally, the update only fires inside the s[i] == s[i-1] branch. This avoids a redundant comparison on run-break steps at the cost of a subtle correctness point (see Invariants).

Dependencies

Imports: None. Pure stdlib, no external libraries.

Imported by: consecutive-characters/test_solution.py (directly). The "Imported By" list in the prompt is misleading — it reflects the test harness's generic import pattern across all problems, not actual consumers of maxPower.

Flow

1. Initialize both max_count and count to 1 (a single character is always a valid run).

2. Iterate i from 1 to len(s) - 1.

3. If s[i] == s[i-1]: extend the current run (count += 1), update max_count if this run is now the longest.

4. Otherwise: reset count = 1 (new run starting at i).

5. Return max_count.

The data transformation is trivial — a string goes in, a single integer comes out. No mutation of input.

Invariants

Error Handling

None. No validation, no exceptions, no edge-case guards. The method trusts the caller to provide a non-empty string, per LeetCode's problem constraints. An empty string input would silently return an incorrect result (1) rather than raising.