Lexicographically Smallest String After Substring Operation - Problem

Given a string s consisting of lowercase English letters. You must perform exactly one operation:

Operation: Select any non-empty substring and 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.

Input & Output

Example 1 — Non-'a' Character
$ Input: s = "cba"
Output: "bba"
💡 Note: We can select the substring "c" and change it to "b". The resulting string "bba" is lexicographically smallest possible.
Example 2 — All 'a' Characters
$ Input: s = "aaa"
Output: "aaz"
💡 Note: Since all characters are 'a', we must change at least one. Changing the last 'a' to 'z' gives us "aaz", which is lexicographically smallest.
Example 3 — Mixed Characters
$ Input: s = "abcxyz"
Output: "aacxyz"
💡 Note: The first non-'a' character is 'b' at position 1. Changing 'b' to 'a' gives "aacxyz".

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters only

Visualization

Tap to expand
Transform String to Get Lexicographically Smallest ResultRule: Each letter becomes previous letter (b→a, c→b, but a→z)cbaInput:Choose optimal substringbbaOutput:"bba" - Lexicographically Smallest PossibleStrategy: Change leftmost non-'a' character (or last 'a' if all are 'a')
Understanding the Visualization
1
Input String
Given string with lowercase letters
2
Find Optimal Position
Choose best substring to minimize result
3
Apply Operation
Decrement characters in chosen substring
Key Takeaway
🎯 Key Insight: To minimize lexicographically, change the leftmost character that can become smaller
Asked in
Google 25 Microsoft 18
23.5K Views
Medium Frequency
~15 min Avg. Time
890 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