Remove Adjacent Almost-Equal Characters - Problem

You are given a 0-indexed string word. In one operation, you can pick any index i of word and change word[i] to any lowercase English letter.

Return the minimum number of operations needed to remove all adjacent almost-equal characters from word.

Two characters a and b are almost-equal if:

  • a == b (same character), or
  • a and b are adjacent in the alphabet (like 'a' and 'b', or 'p' and 'q')

Input & Output

Example 1 — Basic Conflict
$ Input: word = "abb"
Output: 1
💡 Note: Characters at positions 1 and 2 are both 'b' (almost-equal). Change word[2] to any character that's not adjacent to 'b', like 'd'. Result: "abd" with 1 operation.
Example 2 — Adjacent Letters
$ Input: word = "abc"
Output: 1
💡 Note: Characters 'b' and 'c' are adjacent in alphabet (almost-equal). Change 'c' to a non-adjacent character like 'e'. Result: "abe" with 1 operation.
Example 3 — No Changes Needed
$ Input: word = "ace"
Output: 0
💡 Note: No adjacent characters are almost-equal: 'a' and 'c' differ by 2, 'c' and 'e' differ by 2. No operations needed.

Constraints

  • 1 ≤ word.length ≤ 105
  • word consists only of lowercase English letters

Visualization

Tap to expand
Remove Adjacent Almost-Equal Characters INPUT word = "abb" a i=0 b i=1 b i=2 Almost-Equal Pairs: 'a' and 'b' are adjacent 'b' and 'b' are equal Both pairs need checking! adj equal Input Values: word = "abb" ALGORITHM STEPS 1 Initialize ops = 0, i = 1 2 Check i=1: 'a','b' |a-b| = 1, adjacent! But keep going... 3 Check i=2: 'b','b' |b-b| = 0, EQUAL! ops++, skip next 4 Greedy Choice Change word[2]='b' to 'd' (skip i=3) Greedy Strategy: When pair found, change 2nd char and skip ahead "abb" ---> "abd" FINAL RESULT Modified string: a b d changed 'a','b': adj but OK 'b','d': not adj OK OUTPUT 1 Minimum operations: 1 All pairs now valid! Key Insight: When we find an almost-equal pair at positions i and i+1, we greedily change the character at i+1. After changing, we skip to i+2 since the new character won't conflict with the next one. Time: O(n) | Space: O(1) - Single pass through the string with constant extra space. TutorialsPoint - Remove Adjacent Almost-Equal Characters | Greedy - Single Pass Optimization
Asked in
Google 25 Meta 18 Amazon 15
23.4K Views
Medium Frequency
~15 min Avg. Time
845 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