Description
Given a string s consisting of lowercase English letters. Perform the following operation:
- Select any non-empty substring then replace every letter of the substring with the preceding letter of the English alphabet. For example, 'b' is converted to 'a', and 'a' is converted to 'z'.
 
Return the lexicographically smallest string after performing the operation.
Β
Example 1:
Input: s = "cbabc"
Output: "baabc"
Explanation:
Perform the operation on the substring starting at index 0, and ending at index 1 inclusive.
Example 2:
Input: s = "aa"
Output: "az"
Explanation:
Perform the operation on the last letter.
Example 3:
Input: s = "acbbc"
Output: "abaab"
Explanation:
Perform the operation on the substring starting at index 1, and ending at index 4 inclusive.
Example 4:
Input: s = "leetcode"
Output: "kddsbncd"
Explanation:
Perform the operation on the entire string.
Β
Constraints:
1 <= s.length <= 3 * 105sconsists of lowercase English letters
Solution
Python3
class Solution:
    def smallestString(self, s: str) -> str:
        N = len(s)
        start = 0
        others = 0
        
        def transform(start, end):
            A = list(s)
            
            for i in range(start, end + 1):
                A[i] = chr(ord(s[i]) - 1)
                
            return "".join(A)
        
        for i, x in enumerate(s):
            if x == 'a':
                if i == 0 or others == 0:
                    start = i + 1
                    continue
                
                return transform(start, i - 1)
            else:
                others += 1
        
        if others == 0:
            A = list(s)
            
            A[-1] = 'z'
            
            return "".join(A)
            
        return transform(start, N - 1)