File: replace-all-s-to-avoid-consecutive-repeating-characters/solution.py

Date: 2026-06-06

Time: 18:51

replace-all-s-to-avoid-consecutive-repeating-characters/solution.py

Purpose

This file solves LeetCode 1576: Replace All ?'s to Avoid Consecutive Repeating Characters. It owns both the solution logic and its test suite in a single module. The problem directory name uses s in place of ? because ? is not filesystem-safe.

Key Components

Solution.dfs(self, s: str) -> str — The core solver. Despite the name dfs, this is a greedy linear scan, not a depth-first search. It iterates through the string once, replacing each ? with the first character from 'abc' that doesn't conflict with either neighbor. The method name is misleading — there's no recursion, no backtracking, and no search tree.

TestSolution — A unittest.TestCase covering the LeetCode examples plus edge cases (single ?, all ?s, no ?s, ? between identical neighbors). Because the problem has multiple valid outputs, most tests assert structural properties (no consecutive repeats, non-? characters preserved) rather than exact strings.

assertno_consecutive(self, s) — A test helper that verifies the primary invariant: no two adjacent characters are equal. Used by nearly every test method.

Patterns

Dependencies

Imports: Only unittest from the standard library. No external dependencies.

Imported by: The testsolution.py in this same directory imports from it (as listed in the importedby section). The massive imported_by list in the prompt is an artifact of the repo's cross-referencing — those are other problems' test files, not actual importers of this module.

Flow

1. Convert input string to a list of characters.

2. For each index i in [0, n):

3. Join and return.

The right-neighbor check (chars[i+1]) works correctly even when chars[i+1] is itself a ? — in that case no candidate will match '?', so the check is vacuously satisfied. The ? at i+1 will be resolved when the loop reaches it.

Invariants

Error Handling

None. The code assumes valid input per LeetCode constraints (lowercase letters and ? only). There's no handling for empty strings, but range(0) produces an empty loop, so "" returns "" correctly.