2734. Lexicographically Smallest String After Substring Operation
SourceWeekly Contest 349 Q2DifficultyMediumRating1405
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
Solutions
Solution 1: Greedy Algorithm
Thinking
We must decrement every letter in one contiguous substring once (\(a\) wraps to \(z\)) and want the lexicographically smallest result. Trying every substring is impossible at \(n\le 10^5\).
Decrementing \(a\) yields \(z\), so \(a\) should be avoided. Starting at the leftmost non-\(a\) run and stopping before the next \(a\) drops the earliest possible position. If the string is all \(a\), the mandatory operation turns the last character into \(z\).
We can traverse the string \(s\) from left to right, find the position \(i\) of the first character that is not 'a', and then find the position \(j\) of the first 'a' character starting from \(i\). We decrement each character in \(s[i:j]\), and finally return the processed string.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the string \(s\).
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |