Lexicographically Smallest String After Reverse Problem
#3722
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3722.
You are given a string s of length n consisting of lowercase English letters.
You must perform exactly one operation by choosing any integer k such that 1 <= k <= n and either:
- reverse the first
kcharacters ofs, or - reverse the last
kcharacters ofs.
Return the lexicographically smallest string that can be obtained after exactly one such operation.
Example 1:
Input: s = "dcab"
Output: "acdb"
Explanation:
- Choose k = 3, reverse the first 3 characters.
- Reverse "dca" to "acd", resulting string s = "acdb", which is the lexicographically smallest string achievable.
Example 2:
Input: s = "abba"
Output: "aabb"
Explanation:
- Choose k = 3, reverse the last 3 characters.
- Reverse "bba" to "abb", so the resulting string is "aabb", which is the lexicographically smallest string achievable.
Example 3:
Input: s = "zxy"
Output: "xzy"
Explanation:
- Choose k = 2, reverse the first 2 characters.
- Reverse "zx" to "xz", so the resulting string is "xzy", which is the lexicographically smallest string achievable.
Constraints:
1 <= n == s.length <= 1000sconsists of lowercase English letters.
Solution
Approach: Enumeration
Try every k from 1 to n. For each one, build the string obtained by reversing the first k characters and the string obtained by reversing the last k characters, and keep the smallest string seen.
Complexity: time O(n^2), space O(n), where n is the length of the string.
class Solution:
def lexSmallest(self, s: str) -> str:
ans = s
for k in range(1, len(s) + 1):
t1 = s[:k][::-1] + s[k:]
t2 = s[:-k] + s[-k:][::-1]
ans = min(ans, t1, t2)
return ans