#1576

Replace All ?'s to Avoid Consecutive Repeating Characters

Easy
StringTwo PointersGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution processes the string in a single pass, replacing '?' with a character that avoids consecutive duplicates by checking adjacent characters. This is efficient and straightforward.

⚙️

Algorithm

4 steps
  1. 1Step 1: Convert the string into a list for mutability.
  2. 2Step 2: Iterate through each character in the string.
  3. 3Step 3: When encountering a '?', choose a character that is different from the previous and next characters.
  4. 4Step 4: Replace '?' with the chosen character.
solution.py11 lines
1s = '?zs'
2result = list(s)
3for i in range(len(result)):
4    if result[i] == '?':
5        for c in 'abcdefghijklmnopqrstuvwxyz':
6            if (i > 0 and result[i-1] == c) or (i < len(result)-1 and result[i+1] == c):
7                continue
8            result[i] = c
9            break
10final_string = ''.join(result)
11print(final_string)

Complexity note: The complexity is O(n) because we traverse the string once, and each replacement is done in constant time.

  • 1Always check adjacent characters when replacing '?' to avoid duplicates.
  • 2Iterating through the string in a single pass is more efficient than backtracking.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.