Remove Adjacent Almost-Equal Characters - Problem
Remove Adjacent Almost-Equal Characters

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
Garden Path Stone ArrangementABCCConflict!Conflict!RedPinkCyanCyanStep 1: Identify conflicts between similar colorsADCFStep 2: Repaint stones to safe colors - 2 operations needed!๐Ÿ’ก Key Insight: Always change the second stone in a conflict for maximum flexibility!
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.
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
42.3K Views
Medium-High Frequency
~18 min Avg. Time
1.8K 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