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
Lexicographically Smallest String After Substring Operation INPUT String s = "cba" c index 0 b index 1 a index 2 Character Values: 'a'=97, 'b'=98, 'c'=99 Goal: Find substring to decrement that gives smallest result 'a' wraps to 'z' (avoid!) ALGORITHM STEPS 1 Skip leading 'a's Find first char != 'a' c Start here! 2 Decrement chars Until we hit 'a' c --> b OK 3 Process index 1 'b' != 'a', decrement b --> a OK 4 Stop at 'a' Don't wrap to 'z'! 'a' at idx 2 STOP FINAL RESULT Output: "bba" b c --> b b b --> a a unchanged Comparison: Before: "cba" After: "bba" Verification: "bba" < "cba" Lexicographically smaller - OK Key Insight: Greedy approach: Skip all leading 'a's, then decrement consecutive non-'a' characters. Stop when hitting 'a' to avoid wrapping to 'z'. If entire string is 'a's, change last char to 'z'. TutorialsPoint - Lexicographically Smallest String After Substring Operation | Greedy - Optimal Single Pass
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