#3722
Lexicographically Smallest String After Reverse
MediumTwo PointersBinary SearchEnumerationString ManipulationTwo Pointers
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 generating all combinations, we can directly compare the results of reversing the first k and last k characters, keeping track of the smallest string as we iterate.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to store the smallest string as the original string.
- 2Step 2: Loop through k from 1 to n.
- 3Step 3: For each k, compute the two potential strings and update the smallest string accordingly.
solution.py7 lines
1def smallestString(s):
2 smallest = s
3 for k in range(1, len(s) + 1):
4 rev_first = s[:k][::-1] + s[k:]
5 rev_last = s[:-k] + s[-k:][::-1]
6 smallest = min(smallest, rev_first, rev_last)
7 return smallestℹ
Complexity note: We only iterate through the string once for each k, leading to O(n) time complexity.
- 1Reversing affects the order of characters significantly.
- 2Lexicographical order can be determined by string comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.