Python 1576.py
class Solution:
def modifyString(self, s: str) -> str:
result = []
for i, c in enumerate(s):
# keep normal characters
if c != "?":
result.append(c)
continue
# "neighbors"
prev = "" if i == 0 else result[-1]
next = "" if i == len(s) - 1 else s[i + 1]
# three candidates are sufficient to handle all situtations
replace = [ "a", "b", "c" ]
for r in replace:
if prev != r and next != r:
result.append(r)
break
return "".join(result)
Difficulty
and has an acceptance rate of about 45% (100k+ submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided modifyString method receives a string that may contain the placeholder character ?. Its purpose is to produce a new string where every ? is replaced by a lowercase letter such that no two adjacent characters are identical. The algorithm proceeds left-to-right, constructing the result incrementally.
Key Steps
Iterating through the input string
The function walks through each character together with its index using Python’s enumerate.
for i, c in enumerate(s):
Handling non-placeholder characters
When the current character is not a ?, it is copied directly into the result list and the loop continues to the next position.
if c != "?":
result.append(c)
continue
Determining neighboring characters
For a placeholder, the algorithm identifies the character that will appear to its left (prev) and the character that currently resides to its right in the original string (next). Edge positions are treated specially: the first character has no left neighbor, and the last character has no right neighbor.
prev = "" if i == 0 else result[-1]
next = "" if i == len(s) - 1 else s[i + 1]
Selecting a replacement character
A small fixed set of candidates-"a", "b", and "c"-is examined in order. The first candidate that differs from both prev and next is chosen and appended to the result. Because only three distinct letters are needed to guarantee a valid choice, the loop always terminates quickly.
replace = [ "a", "b", "c" ]
for r in replace:
if prev != r and next != r:
result.append(r)
break
Building the final string
After processing all characters, the list of characters is joined into a single string, which is returned as the final output.
return "".join(result)
Edge Cases Addressed
The implementation explicitly handles the situation where a placeholder appears at the very beginning of the string. In that case prev is set to an empty string, ensuring that the replacement decision only depends on the right neighbor. Similarly, when a placeholder is at the end, next becomes an empty string, allowing the algorithm to focus solely on the left neighbor.
Consecutive placeholders are also covered. As the result list is updated immediately after each replacement, the left neighbor for a later placeholder reflects the character chosen for the preceding one. This guarantees that no two adjacent positions end up with the same letter, even when the original string contains a run of ? characters.
If the original string contains no placeholders, the loop copies each character unchanged, and the function returns the input string verbatim.
Performance Optimizations
The code builds the output using a list (result) rather than concatenating strings on each iteration. This avoids the quadratic cost associated with repeated string concatenation in Python, leading to linear-time construction of the final result.
The candidate list for replacements is limited to three letters. Because only three distinct options are needed to satisfy the adjacency constraint, the inner loop performs at most three comparisons per placeholder, providing a predictable and minimal amount of work.
The early continue after handling a non-placeholder character prevents unnecessary execution of the neighbor-determination and replacement logic for positions that do not require modification, further reducing the amount of work performed.
ELI5 - Simplified Explanation
Imagine you have a long row of building blocks, and some of them are mystery blocks with a question mark on them. This code is like a little robot helper that walks along the row to fix those mystery blocks.
The robot looks at each block one by one. If a block already has a letter on it, the robot just leaves it alone and moves to the next one. When the robot finds a mystery block that needs a label, it stops to look at the blocks immediately to the left and the right.
To pick the perfect letter for the mystery spot, the robot tries out three choices: a, b, and c. It checks its neighbors on both sides to make sure the letter it picks is different from the blocks touching it. Once the robot finds a letter that is not the same as the neighbor on the left or the right, it clicks that letter onto the mystery spot. After checking every single block and filling in all the blanks, the robot puts all the blocks back together into one smooth line.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | Python | C++ | Java | TS | ||||
| WalkCCC | Python | C++ | Java | ||||||
| leetcode.ca | Python | C++ | Go | Java | TS | ||||
| Progiez | Python | C++ | Java | ||||||
| github | everthis | JS | |||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| YuriSpiridonov | Python |
Solved On The Same Day
- problem 1360: Number of Days Between Two Dates
- problem 1716: Calculate Money in Leetcode Bank
- problem 2409: Count Days Spent Together
- problem 2515: Shortest Distance to Target String in a Circular Array
- problem 2644: Find the Maximum Divisibility Score
- problem 1110: Delete Nodes And Return Forest
- problem 1296: Divide Array in Sets of K Consecutive Numbers
- problem 1443: Minimum Time to Collect All Apples in a Tree
- problem 1669: Merge In Between Linked Lists
- problem 458: Poor Pigs
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality