Minimum Operations to Transform String Problem
Description
LeetCode Problem 3675.
You are given a string s consisting only of lowercase English letters.
You can perform the following operation any number of times (including zero):
- Choose any character
cin the string and replace every occurrence ofcwith the next lowercase letter in the English alphabet.
Return the minimum number of operations required to transform s into a string consisting of only 'a' characters.
Note: Consider the alphabet as circular, thus 'a' comes after 'z'.
Example 1:
Input: s = "yz"
Output: 2
Explanation:
- Change 'y' to 'z' to get "zz".
- Change 'z' to 'a' to get "aa".
- Thus, the answer is 2.
Example 2:
Input: s = "a"
Output: 0
Explanation:
- The string "a" only consists of 'a' characters. Thus, the answer is 0.
Constraints:
1 <= s.length <= 5 * 10^5sconsists only of lowercase English letters.
Solution
Approach: Farthest Letter From 'a'
Replacing a letter replaces every occurrence of it, so letters that are already equal stay equal. Once a letter has become the next one, all that is left is to keep pushing the group forward until it reaches 'a'. Operations on different letters can share their work: if we always move the letters in order 'b', 'c', ..., each step also carries along every letter that has already merged into it.
So the answer is the number of steps the letter farthest from 'a' needs to wrap around to 'a'. A letter c other than 'a' needs 26 - (c - 'a') steps, and 'a' needs none. Take the maximum over the string.
Complexity: O(n) time and O(1) extra space, where n is the length of s.
class Solution:
def minOperations(self, s: str) -> int:
return max((26 - (ord(c) - 97) for c in s if c != "a"), default=0)