#2957
Remove Adjacent Almost-Equal Characters
MediumStringDynamic ProgrammingGreedyGreedyDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a greedy approach where we iterate through the string and change characters only when necessary. This ensures we minimize the number of operations while maintaining the constraints.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a counter for operations needed.
- 2Step 2: Iterate through the string from the first character to the last.
- 3Step 3: For each character, check if it is almost-equal to the previous character. If it is, increment the operation counter and change the character to a valid non-adjacent character.
solution.py12 lines
1def min_operations(word):
2 operations = 0
3 n = len(word)
4 for i in range(1, n):
5 if abs(ord(word[i]) - ord(word[i - 1])) <= 1:
6 operations += 1
7 # Change to a non-adjacent character
8 if word[i - 1] == 'z':
9 word = word[:i] + 'x' + word[i + 1:]
10 else:
11 word = word[:i] + chr(ord(word[i - 1]) + 2) + word[i + 1:]
12 return operationsℹ
Complexity note: The complexity is O(n) because we only make a single pass through the string, checking each character against its predecessor.
- 1Adjacent characters can be efficiently handled by ensuring we change them to a character that is not adjacent to either neighbor.
- 2The greedy approach minimizes changes by making local optimal choices.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.