Date: 2026-06-06
Time: 18:51
replace-all-s-to-avoid-consecutive-repeating-characters/solution.pyThis 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.
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.
'a', 'b', 'c' are tried as replacements. This works because any position has at most 2 neighbors, so 3 candidates always guarantees a valid choice.chars = list(s) converts the immutable string to a list for O(1) in-place updates, then ''.join(chars) converts back.assertno_consecutive, assertNotEqual against neighbors) rather than pinning to a specific valid output. This is the right pattern for problems with multiple correct answers.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.
1. Convert input string to a list of characters.
2. For each index i in [0, n):
chars[i] != '?'.'a', then 'b', then 'c':chars[i-1]) or the right neighbor (chars[i+1]), skip it.break.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.
? characters and no two adjacent characters are equal.? is resolved using already-resolved left neighbors and unresolved right neighbors. This is safe because the right neighbor either isn't ? (so the check is meaningful) or is ? (so no candidate matches it, and it will be resolved later with awareness of the choice made here).'abc' will always find a match and break.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.