Lexicographically Smallest String After Substring Operation Problem
#2734
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2734.
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 * 10^5sconsists of lowercase English letters
Solution
Approach: Greedy
Decreasing a letter makes the string smaller, except for 'a', which would wrap around to 'z' and make it larger. So we want to start decreasing at the first character that is not 'a', and to continue as far as possible without touching an 'a'.
- Find the first index
iwiths[i] != 'a'. - If there is none (the string is all
'a'), we must change something: the best choice is to change only the last character into'z'. - Otherwise find the first
'a'at or afteri, call its indexj(ornif there is none), and decrease every character ofs[i..j-1]by one.
Complexity: O(n) time and O(n) space for the result.
class Solution:
def smallestString(self, s: str) -> str:
n = len(s)
i = 0
while i < n and s[i] == "a":
i += 1
if i == n:
return s[:-1] + "z"
j = i
while j < n and s[j] != "a":
j += 1
return s[:i] + "".join(chr(ord(c) - 1) for c in s[i:j]) + s[j:]