Remove Adjacent Almost-Equal Characters - Problem
Remove Adjacent Almost-Equal Characters
You're given a string
Two characters are considered almost-equal if:
โข They are identical (like 'a' and 'a')
โข They are consecutive in the alphabet (like 'a' and 'b', or 'p' and 'q')
In each operation, you can pick any index and change that character to any lowercase letter. Find the minimum number of operations needed so that no two adjacent characters in the final string are almost-equal.
Example: In
You're given a string
word containing lowercase English letters. Your task is to eliminate all pairs of adjacent characters that are "almost-equal" by changing some characters to different letters.Two characters are considered almost-equal if:
โข They are identical (like 'a' and 'a')
โข They are consecutive in the alphabet (like 'a' and 'b', or 'p' and 'q')
In each operation, you can pick any index and change that character to any lowercase letter. Find the minimum number of operations needed so that no two adjacent characters in the final string are almost-equal.
Example: In
"abcc", we have almost-equal pairs: (a,b) and (c,c). We need at least 1 operation to fix this. Input & Output
example_1.py โ Basic case with multiple conflicts
$
Input:
word = "abcc"
โบ
Output:
2
๐ก Note:
We have conflicts: (a,b) are consecutive in alphabet, and (c,c) are identical. We can change 'b' to 'd' and the last 'c' to 'f', giving us "adcf". This requires 2 operations.
example_2.py โ Single character
$
Input:
word = "a"
โบ
Output:
0
๐ก Note:
A single character has no adjacent pairs, so no operations are needed.
example_3.py โ No conflicts initially
$
Input:
word = "aceg"
โบ
Output:
0
๐ก Note:
No adjacent characters are almost-equal. 'a' and 'c' differ by 2, 'c' and 'e' differ by 2, 'e' and 'g' differ by 2. No operations needed.
Constraints
- 1 โค word.length โค 105
- word consists of lowercase English letters only
- Almost-equal characters: identical (a==a) or consecutive in alphabet (a,b or p,q)
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Path
Walk along the garden path and identify pairs of adjacent stones that have conflicting colors
2
Strategic Repainting
When you find conflicting stones, always repaint the second stone in the pair to give maximum flexibility
3
Choose Wisely
Pick a new color that won't conflict with the stone before it or the stone after it
4
Continue Forward
Move to the next stone and repeat the process until the entire path is conflict-free
Key Takeaway
๐ฏ Key Insight: The greedy strategy of always changing the second character in a conflicting pair is optimal because it preserves all previous decisions while providing maximum flexibility for future choices.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code