Replace All ?'s to Avoid Consecutive Repeating Characters - Problem

You're given a string s containing lowercase English letters and mysterious ? characters. Your mission is to replace every question mark with a lowercase letter such that no two adjacent characters in the final string are identical.

Think of the question marks as blank spaces that need to be filled wisely. You cannot change any existing letters - only the question marks are yours to modify.

The good news: The input string is guaranteed to have no consecutive repeating letters among the non-? characters, so a solution always exists!

Goal: Return any valid string where all ? characters have been replaced with letters, and no two consecutive characters are the same.

Example: "?zs" could become "azs" or "bzs", but not "zzs" since that would create consecutive identical characters.

Input & Output

example_1.py โ€” Basic replacement
$ Input: s = "?zs"
โ€บ Output: "azs"
๐Ÿ’ก Note: We replace the '?' with 'a' because it doesn't match its right neighbor 'z'. The result "azs" has no consecutive repeating characters.
example_2.py โ€” Multiple question marks
$ Input: s = "ubv?w"
โ€บ Output: "ubvaw"
๐Ÿ’ก Note: The '?' is surrounded by 'v' and 'w'. We can use 'a' since it doesn't conflict with either neighbor.
example_3.py โ€” Edge case with conflicts
$ Input: s = "a?c"
โ€บ Output: "abc"
๐Ÿ’ก Note: The '?' cannot be 'a' (left neighbor) or 'c' (right neighbor), so we use 'b' as the first valid option.

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists of lowercase English letters and '?' characters only
  • No consecutive repeating characters exist in the input (except '?')
  • A solution always exists with the given constraints

Visualization

Tap to expand
๐Ÿฝ๏ธ Restaurant Seating AnalogyA?C?OccupiedEmptyOccupiedEmptySeating First Empty Table:โŒ Can't use A (left neighbor)โŒ Can't use C (right neighbor)โœ… Use B (no conflicts!)ABCAFinal Seating: A-B-C-A โœจ๐ŸŽฏ Key: Check only immediate neighbors, choose greedily!
Understanding the Visualization
1
Walk Through Tables
Move from left to right, checking each empty table
2
Check Neighbors
Look at who's sitting on the left and right of empty table
3
Choose Personality
Pick the first personality type (A, B, C) that won't clash
4
Seat Customer
Place the customer and move to next empty table
Key Takeaway
๐ŸŽฏ Key Insight: Since we only need to avoid conflicts with immediate neighbors (at most 2 characters), we can always find a valid letter among 'a', 'b', 'c' using a greedy approach. This makes the problem much simpler than it initially appears!
Asked in
Google 12 Facebook 8 Amazon 6 Microsoft 4
23.4K Views
Medium Frequency
~12 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen