Given a string s
consisting of lowercase English letters. Perform the following operation:
Return the lexicographically smallest string after performing the operation.
Example 1:
Input: s = "cbabc" Output: "baabc" Explanation: Perform the operation on the substring starting at index 0, and ending at index 1 inclusive.
Example 2:
Input: s = "aa" Output: "az" Explanation: Perform the operation on the last letter.
Example 3:
Input: s = "acbbc" Output: "abaab" Explanation: Perform the operation on the substring starting at index 1, and ending at index 4 inclusive.
Example 4:
Input: s = "leetcode" Output: "kddsbncd" Explanation: Perform the operation on the entire string.
def smallest_string(s):
n = len(s)
arr = list(s)
start = -1
for i in range(n):
if s[i] != 'a':
start = i
break
if start == -1:
arr[-1] = 'z'
return "".join(arr)
end = start
while end < n and arr[end] != 'a':
arr[end] = chr(ord(arr[end]) - 1)
end += 1
return "".join(arr)
# Example Usage
print(smallest_string("cbabc")) # Output: "baabc"
print(smallest_string("aa")) # Output: "az"
print(smallest_string("acbbc")) # Output: "abaab"
print(smallest_string("leetcode")) # Output: "kddsbncd"
The problem requires us to find the lexicographically smallest string after performing an operation where we select a substring and decrement each character in that substring (wrapping 'a' to 'z').
Naive Approach:
Optimal Approach:
s
to find the first character that is not 'a'.The optimal solution has a time complexity of O(N), where N is the length of the string s
.
The space complexity of the optimal solution is O(N), where N is the length of the string s
.
s
to a list arr
to modify the characters in place. This list requires O(N) space.start
, end
) take constant space O(1).