Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers · Binary Search
Example 1
"dcab"
Example 2
"abba"
Example 3
"zxy"
Step 02
Core Insight
What unlocks the optimal approach
Use bruteforce
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3722: Lexicographically Smallest String After Reverse
class Solution {
public String lexSmallest(String s) {
String ans = s;
int n = s.length();
for (int k = 1; k <= n; ++k) {
String t1 = new StringBuilder(s.substring(0, k)).reverse().toString() + s.substring(k);
String t2 = s.substring(0, n - k)
+ new StringBuilder(s.substring(n - k)).reverse().toString();
if (t1.compareTo(ans) < 0) {
ans = t1;
}
if (t2.compareTo(ans) < 0) {
ans = t2;
}
}
return ans;
}
}
// Accepted solution for LeetCode #3722: Lexicographically Smallest String After Reverse
func lexSmallest(s string) string {
ans := s
n := len(s)
for k := 1; k <= n; k++ {
t1r := []rune(s[:k])
slices.Reverse(t1r)
t1 := string(t1r) + s[k:]
t2r := []rune(s[n-k:])
slices.Reverse(t2r)
t2 := s[:n-k] + string(t2r)
ans = min(ans, t1, t2)
}
return ans
}
# Accepted solution for LeetCode #3722: Lexicographically Smallest String After Reverse
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
// Accepted solution for LeetCode #3722: Lexicographically Smallest String After Reverse
fn lex_smallest(s: String) -> String {
let cs: Vec<_> = s.chars().collect();
let len = s.len();
let mut ret = cs.clone();
for i in 2..=len {
let mut tmp = cs.clone();
let limit2 = i / 2;
for j in 0..limit2 {
tmp.swap(j, i - 1 - j);
}
ret = std::cmp::min(ret, tmp);
}
for i in 2..=len {
let mut tmp = cs.clone();
let limit2 = i / 2;
for j in 0..limit2 {
tmp.swap(len - 1 - j, len - i + j);
}
ret = std::cmp::min(ret, tmp);
}
ret.into_iter().collect()
}
fn main() {
let ret = lex_smallest("dcab".to_string());
println!("ret={ret}");
}
#[test]
fn test() {
assert_eq!(lex_smallest("a".to_string()), "a");
assert_eq!(lex_smallest("abc".to_string()), "abc");
assert_eq!(lex_smallest("dcba".to_string()), "abcd");
assert_eq!(lex_smallest("dcab".to_string()), "acdb");
assert_eq!(lex_smallest("abba".to_string()), "aabb");
assert_eq!(lex_smallest("zxy".to_string()), "xzy");
}
// Accepted solution for LeetCode #3722: Lexicographically Smallest String After Reverse
function lexSmallest(s: string): string {
let ans = s;
const n = s.length;
for (let k = 1; k <= n; ++k) {
const t1 = reverse(s.slice(0, k)) + s.slice(k);
const t2 = s.slice(0, n - k) + reverse(s.slice(n - k));
ans = [ans, t1, t2].sort()[0];
}
return ans;
}
function reverse(s: string): string {
return s.split('').reverse().join('');
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n^2)
Space
O(n)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Boundary update without `+1` / `-1`
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.