#2734
Lexicographically Smallest String After Substring Operation
MediumStringGreedyGreedyString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking all substrings, we can directly find the leftmost character that is not 'a' and replace all characters from that point onward. This is efficient because it guarantees the smallest lexicographical order by minimizing the first non-'a' character.
⚙️
Algorithm
3 steps- 1Step 1: Find the index of the first character that is not 'a'.
- 2Step 2: Replace all characters from that index to the end of the string with their preceding characters.
- 3Step 3: If the string is all 'a's, replace the last character with 'z'.
solution.py6 lines
1def lexicographically_smallest_string(s):
2 n = len(s)
3 first_non_a = next((i for i, c in enumerate(s) if c != 'a'), n)
4 if first_non_a == n:
5 return s[:-1] + 'z'
6 return s[:first_non_a] + ''.join(chr(ord(c) - 1) if c != 'a' else 'z' for c in s[first_non_a:])ℹ
Complexity note: The time complexity is O(n) because we only traverse the string a couple of times. The space complexity is O(n) due to the new string we create for the result.
- 1Finding the first non-'a' character is crucial for minimizing the string.
- 2Replacing characters efficiently can lead to significant performance improvements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.