LeetCode solutions

2828. Lexicographically Smallest String After Substring Operation

My accepted Python solution to LeetCode problem 2828, Lexicographically Smallest String After Substring Operation, running in 103ms.

  • Difficulty: Medium
  • Python
  • Runtime 103ms
  • Memory 22.6MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 103ms, memory 22.6MB, accepted 2025-12-31.

python
class Solution:
    def smallestString(self, s: str) -> str:
        s = list(s)
        n = len(s)
        
        # Find first character that is not 'a'
        i = 0
        while i < n and s[i] == 'a':
            i += 1
        
        # If all characters are 'a', change last character to 'z'
        if i == n:
            s[-1] = 'z'
            return ''.join(s)
        
        # Decrement characters until we hit 'a' or end of string
        while i < n and s[i] != 'a':
            s[i] = chr(ord(s[i]) - 1)
            i += 1
        
        return ''.join(s)

Source