[LeetCode] Lexicographically Smallest String After Reverse

3722. Lexicographically Smallest String After Reverse

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 k characters of s, or
  • reverse the last k characters of s.

Return the lexicographically smallest string that can be obtained after exactly one such operation.

A string a is lexicographically smaller than a string b if, at the first position where they differ, a has a letter that appears earlier in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters are the same, then the shorter string is considered lexicographically smaller.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string lexSmallest(string s) {
int n = s.length();
string res = s;
for(int i = 2; i <= n; i++) {
reverse(begin(s), begin(s) + i);
res = min(res, s);
reverse(begin(s), begin(s) + i);
reverse(end(s) - i, end(s));
res = min(res, s);
reverse(end(s) - i, end(s));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/28/PS/LeetCode/lexicographically-smallest-string-after-reverse/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.