Problem 1576

Abstract / Summary

Given a string, determine if it is a valid palindrome considering only alphanumeric characters and ignoring case differences.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
21 lines | 675 bytes | submitted December 6, 2023 | GitHub   20% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (100k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.89 | σ = 0.74

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
26 links | 15 authors | 8 languages

Solved On The Same Day

11 solutions   December 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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