Lexicographically Smallest String After Substring Operation - Problem
You're given a string s consisting of lowercase English letters. Your task is to make the lexicographically smallest string possible by performing exactly one operation:
- Select any non-empty substring from the string
- Replace every letter in that substring with its preceding letter in the alphabet
- Note:
'b'becomes'a','c'becomes'b', but'a'becomes'z'
Goal: Return the lexicographically smallest string after performing exactly one such operation.
Example: Given "cba", you could select substring "cb" and transform it to "ba", resulting in "baa".
Input & Output
example_1.py โ Basic Case
$
Input:
s = "cba"
โบ
Output:
"baa"
๐ก Note:
We select substring "cb" (indices 0-1) and transform: cโb, bโa. Result: "baa". This is lexicographically smallest among all possible operations.
example_2.py โ All 'a' Case
$
Input:
s = "aaa"
โบ
Output:
"aaz"
๐ก Note:
Since all characters are 'a', transforming any 'a' gives 'z'. To get the lexicographically smallest result, we transform only the last character: "aaa" โ "aaz".
example_3.py โ Mixed Case
$
Input:
s = "acbbc"
โบ
Output:
"aabac"
๐ก Note:
The first non-'a' is 'c' at index 1. We find consecutive non-'a' characters: "c" only. Transform: cโb. Result: "aabbc". Wait, let's recalculate: we should transform "cbb" (indices 1-3): cโb, bโa, bโa. Result: "aabac".
Constraints
- 1 โค s.length โค 105
- s consists of lowercase English letters only
- Must perform exactly one operation
- The selected substring must be non-empty
Visualization
Tap to expand
Understanding the Visualization
1
Scan for Opportunity
Look for the first character that isn't 'a' - this is where we can improve without creating 'z'
2
Maximize Impact
Extend the transformation to include all consecutive non-'a' characters for maximum benefit
3
Handle Edge Case
If the string is all 'a's, transform only the last one to minimize lexicographical impact
Key Takeaway
๐ฏ Key Insight: To minimize lexicographical order, transform the first maximal sequence of non-'a' characters. This avoids creating 'z' characters early in the string while maximizing the improvement from the transformation.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code