Remove Adjacent Almost-Equal Characters Problem
Description
LeetCode Problem 2957.
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 or a and b are adjacent in the alphabet.
Example 1:
Input: word = "aaaaa"
Output: 2
Explanation: We can change word into "acaca" which does not have any adjacent almost-equal characters.
It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2.
Example 2:
Input: word = "abddez"
Output: 2
Explanation: We can change word into "ybdoez" which does not have any adjacent almost-equal characters.
It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2.
Example 3:
Input: word = "zyxyxyz"
Output: 3
Explanation: We can change word into "zaxaxaz" which does not have any adjacent almost-equal characters.
It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 3.
Constraints:
1 <= word.length <= 100wordconsists only of lowercase English letters.
Solution
Approach: Greedy
Scan from the left. When word[i] is almost equal to word[i - 1] (equal or adjacent letters), we change word[i] to a letter that differs from both of its neighbors, which is always possible because 26 letters are plenty. That fix also removes any conflict between word[i] and word[i + 1], so we skip word[i + 1] and continue. We only need to count the changes, not perform them.
Complexity: O(n) time and O(1) extra space.
class Solution:
def removeAlmostEqualCharacters(self, word: str) -> int:
ans = 0
i, n = 1, len(word)
while i < n:
if abs(ord(word[i]) - ord(word[i - 1])) < 2:
ans += 1
i += 2
else:
i += 1
return ans