Ctrl K

Step Back on One Stretch

Medium
You get a string text of lowercase English letters. Exactly once, pick a non-empty stretch of consecutive characters and replace every letter in it with the one before it in the alphabet: b → a, c → b and so on, while a wraps around to z. Return the lexicographically smallest string this operation can produce.
Example 1
text="dbaca" → 'caaca'

The best stretch is db, which turns into ca. Taking the a too would turn it into z.

Example 2
text="abcab" → 'aabab'

There is no point touching the leading a; shift bc into ab.

Example 3
text="aaa" → 'aaz'

The stretch must be non-empty and any a becomes z, so it does the least harm at the very end.

Constraints
  • 1 ≤ len(text) ≤ 3·10⁵
  • text consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Number From Pieces MediumEvery Letter Once MediumErase Digits for the Smallest Number MediumSmallest Up-Down Sequence MediumRing of Flippable Words Medium
loading Python…
Input
text="dbaca"
Expected
'caaca'

Run checks the first 3 tests in your browser. Submit checks all 104 tests on the server, hidden ones included.