We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Lexicographically Smallest String After Substring Operation

Difficulty: Medium


Problem Description

Given a string s consisting of lowercase English letters. Perform the following operation: Select any non-empty substring then 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.


Key Insights

  • The goal is to find a substring that, when modified, results in the smallest possible string.
  • The operation can be applied to any non-empty substring, allowing for flexibility in choosing which characters to modify.
  • The character 'a' can be replaced with 'z', creating a potential for a larger reduction in lexicographic order if strategically applied.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(n)


Solution

To solve this problem, we can iterate over the string while keeping track of the best possible result. For each character, we have the option to either leave it as is or modify it if it leads to a better (smaller) string. We can use a greedy approach to decide when to apply the substring operation. The operation can be efficiently performed by iterating through the string and building the result based on the conditions discussed.


Code Solutions

def lexicographically_smallest_string(s: str) -> str:
    n = len(s)
    result = list(s)  # Convert string to list for mutability

    # We will apply the operation on the first character and see if it's beneficial
    for i in range(n):
        # If the current character is greater than 'a', we can decrease it
        if result[i] > 'a':
            result[i] = chr(ord(result[i]) - 1)  # Move to the preceding character
        else:
            result[i] = 'z'  # If it's 'a', change it to 'z'

    return ''.join(result)  # Convert list back to string
← Back to All Questions