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
Optimal Strategy: Greedy TransformationStrategy: Transform first maximal sequence of consecutive non-'a' charactersException: If all 'a', transform only the last characterCase 1: Normal case with non-'a' charactersInput: "aacbba"aacbbaTransform green sectionResult: "aababa"aabaaaCase 2: All 'a' charactersInput: "aaa" โ†’ Result: "aaz" (transform only last)aazOnly last 'a' transformed
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.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen