Find the Smallest String After One Decrement
Company: Point72
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates string manipulation, lexicographic ordering, and reasoning about local character transformations including wrap-around behavior.
Constraints
- 1 <= len(s) <= 100000
- s contains only lowercase English letters
Examples
Input: "cbabc"
Expected Output: "baabc"
Explanation: Start at the first character. Decrement the substring "cb" to "ba", giving "baabc", which is the smallest possible result.
Input: "abac"
Expected Output: "aaac"
Explanation: Skip the leading `a`. Decrement only the substring "b" to "a" and stop before the next `a`, producing "aaac".
Input: "aaaa"
Expected Output: "aaaz"
Explanation: Every operation must change at least one character, and changing any `a` makes it `z`. To keep the string as small as possible, change only the last character.
Input: "b"
Expected Output: "a"
Explanation: The only valid substring is the whole string. Decrement `b` to `a`.
Input: "aaab"
Expected Output: "aaaa"
Explanation: Skip the leading `a` characters and decrement the final `b` to `a`.
Hints
- Earlier characters matter more in lexicographical order. Try to improve the leftmost possible position without making an earlier character worse.
- Turning an `a` into `z` is usually harmful. What should you do with leading `a` characters, and what if the entire string is all `a`?