Lexicographically Smallest String After Substring Operation — LeetCode 2734 Python Solution
- Problem
- #2734
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Python solution
class Solution:
def smallestString(self, s: str) -> str:
n = len(s)
i = 0
while i < n and s[i] == "a":
i += 1
if i == n:
return s[:-1] + "z"
j = i
while j < n and s[j] != "a":
j += 1
return s[:i] + "".join(chr(ord(c) - 1) for c in s[i:j]) + s[j:]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2734. Lexicographically Smallest String After Substring Operation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2734. Lexicographically Smallest String After Substring Operation?
- LeetCode 2734. Lexicographically Smallest String After Substring Operation is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2734. Lexicographically Smallest String After Substring Operation?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2734. Lexicographically Smallest String After Substring Operation?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2734. Lexicographically Smallest String After Substring Operation cover?
- LeetCode 2734. Lexicographically Smallest String After Substring Operation is tagged Greedy and String on LeetCode.