Quick Overview

This question evaluates string manipulation, lexicographic ordering, and reasoning about local character transformations including wrap-around behavior.

Find the Smallest String After One Decrement

Company: Point72

Role: Machine Learning Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

You are given a string `s` consisting only of lowercase English letters. You must perform exactly one operation: 1. Choose one non-empty contiguous substring of `s`. 2. Replace every character in that substring with the previous character in the alphabet. - For example, `b` becomes `a`, `c` becomes `b`, and so on. - The character `a` wraps around and becomes `z`. Return the lexicographically smallest string that can be obtained after exactly one operation. Example: ```text Input: s = "cbabc" Output: "baabc" ``` Explanation: Choose the substring `"cb"` and decrement it to `"ba"`, producing `"baabc"`.

Quick Answer: This question evaluates string manipulation, lexicographic ordering, and reasoning about local character transformations including wrap-around behavior.

You are given a non-empty string `s` consisting only of lowercase English letters. You must perform exactly one operation: 1. Choose one non-empty contiguous substring of `s`. 2. Replace every character in that substring with the previous character in the alphabet. - `b` becomes `a`, `c` becomes `b`, and so on. - `a` wraps around and becomes `z`. Return the lexicographically smallest string that can be obtained after exactly one operation. Lexicographical order is the same as dictionary order: a string is smaller if it has a smaller character at the first position where the two strings differ.

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".

Hints

  1. Earlier characters matter more in lexicographical order. Try to improve the leftmost possible position without making an earlier character worse.
  2. 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`?

Loading coding console...