Skip to main content
Back to problems
#3722
Medium Algorithms

Lexicographically smallest string after reverse

Two Pointers Binary Search Enumeration
54.7% acceptance
Feb 24, 2026
36
7
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn lex_smallest(s: String) -> String {
    let n = s.len();
    let s: Vec<u8> = s.bytes().collect();
    let mut best = s.clone();
    for k in 1..=n {
      // Reverse first k
      let mut t = s.clone();
      t[..k].reverse();
      if t < best { best = t; }
      // Reverse last k
      let mut t = s.clone();
      t[n - k..].reverse();
      if t < best { best = t; }
    }
    String::from_utf8(best).unwrap()
  }
}