Magicsheet logo

Remove Adjacent Almost-Equal Characters

Medium
75%
Updated 8/1/2025

Remove Adjacent Almost-Equal Characters

What is this problem about?

The Remove Adjacent Almost-Equal Characters problem asks for the minimum number of operations to make no two adjacent characters "almost equal" (differ by at most 1 in ASCII value). In each operation, you change one character to any other. This medium coding problem uses greedy: skip characters when a violation is found (changing every other violating character minimizes operations). The string, greedy, and dynamic programming interview pattern is demonstrated.

Why is this asked in interviews?

Salesforce asks this to test greedy reasoning for minimum character changes. The key insight: when you find a violation at position i, change s[i] (or s[i+1]) and skip to i+2 to avoid re-processing already-resolved positions.

Algorithmic pattern used

Greedy scan with skip. Scan left to right. When |s[i] - s[i-1]| <= 1 (almost equal adjacent pair): increment operation count, skip the next character (i+=2 effectively). Otherwise advance normally. The skip ensures you change s[i] to break the pair and don't re-examine it.

Example explanation

s="aaaa". Scan:

  • i=1: 'a','a' adjacent (diff=0 ≤ 1). ops=1. Skip: next check at i=3.
  • i=3: 'a','a' adjacent. ops=2. Result = 2 operations (change s[1] and s[3]).

s="abcd": |a-b|=1, |b-c|=1, |c-d|=1. All almost-equal. Greedy: op at i=1 (skip i=2). op at i=3. Result = 2.

Common mistakes candidates make

  • Scanning every pair without skipping (overcounts operations).
  • Not understanding why skipping i+1 is optimal.
  • Trying DP unnecessarily (greedy gives optimal answer here).
  • Off-by-one in the skip logic.

Interview preparation tip

Adjacent-pair violation problems often have greedy solutions using "fix and skip." When a violation occurs at position i, fix it and skip the next position (since it can't conflict with the already-fixed position). This greedy achieves the minimum number of changes. Practice: "minimum deletions to avoid adjacent identical characters," "minimum flips to separate alternating bits."

Similar Questions