Skip to main content

Lexicographically Smallest String After Reverse - Solution & Explanation

Practice this problem

Problem Statement

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.

 

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 <= 1000
  • s consists of lowercase English letters.

Approach Overview

Problem Overview: You are given a string and can reverse exactly one substring. The goal is to choose the substring that produces the lexicographically smallest possible result. The challenge is deciding which segment [l, r] to reverse so the resulting string is minimal in dictionary order.

Approach 1: Brute Force Enumeration (O(n^3) time, O(n) space)

The most direct strategy is to try every possible substring reversal. For each pair of indices l and r, reverse the substring s[l:r] and construct the resulting string. Compare it with the current best answer and keep the lexicographically smallest one. This requires generating a new string for each candidate, which costs O(n), while the number of pairs is O(n^2). Total complexity becomes O(n^3) time with O(n) extra space for temporary strings. This brute force approach is useful for understanding the search space but becomes slow for larger inputs.

Approach 2: Optimized Enumeration (O(n^2) time, O(n) space)

You can avoid repeatedly rebuilding full strings by comparing candidates more carefully. Iterate over all starting positions l, and for each l try every possible end position r. Instead of constructing the full reversed string every time, simulate the comparison against the current best answer character by character. The prefix before l stays the same, while the reversed section is accessed using mirrored indices. This reduces the cost of each check and avoids unnecessary copying. The overall process still enumerates O(n^2) substrings, but each comparison exits early once a difference is found, making it practical in typical constraints.

This approach naturally relates to techniques from enumeration, where you systematically explore candidate ranges. During comparison, you effectively simulate reversed traversal similar to a two pointers pattern. Some optimized implementations also use ideas similar to binary search style comparisons when checking lexicographic differences quickly.

Recommended for interviews: Interviewers expect the optimized enumeration solution. Starting with brute force shows you understand the operation space (all [l, r] reversals). Then reduce redundant string construction and compare lazily to reach O(n^2) time. This demonstrates both correctness reasoning and practical optimization.

Solution

We can enumerate all possible values of k (1 leq k leq n). For each k, we compute the string obtained by reversing the first k characters and the string obtained by reversing the last k characters, then take the lexicographically smallest string among them as the final answer.

The time complexity is O(n^2) and the space complexity is O(n), where n is the length of the string.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force EnumerationO(n^3)O(n)Good for understanding the problem or very small strings
Optimized Enumeration with Lazy ComparisonO(n^2)O(n)Preferred solution in interviews and competitive programming

Video Solution

BiWeekly Contest 168 Lexicographically Smallest String After Reverse • R Sai Siddhu • 254 views views

Watch 2 more video solutions →

Frequently Asked Questions

Is Lexicographically Smallest String After Reverse easy or hard?
Lexicographically Smallest String After Reverse is generally considered a Medium difficulty problem. The challenge is recognizing that checking all reversal ranges is feasible while optimizing comparisons to avoid expensive string reconstruction.
Lexicographically Smallest String After Reverse Python/Java solution
A typical implementation iterates through all substring ranges using nested loops. For each pair (l, r), compare the simulated reversed string against the current best result. This enumeration strategy is straightforward to implement in Python, Java, C++, Go, and TypeScript with O(n^2) time complexity.
How to solve Lexicographically Smallest String After Reverse in O(n^2)?
Enumerate all substring boundaries (l, r). Instead of constructing the full reversed string for every pair, simulate the reversed portion during comparison with the best string so far. Stop comparison early when characters differ. This avoids repeated string creation and keeps the runtime around O(n^2).
What is the best approach for Lexicographically Smallest String After Reverse?
The optimized enumeration approach is the most practical solution. Iterate over all possible substring ranges and compare the resulting string with the current best candidate without rebuilding the entire string each time. This reduces the complexity to O(n^2) time and O(n) space while still checking every valid reversal.
Is Lexicographically Smallest String After Reverse asked at Google/Amazon/Meta?
Problems involving lexicographic minimization and substring operations appear frequently in interviews at companies like Google, Amazon, and Meta. Variants often test reasoning about string transformations, greedy decisions, and efficient comparison techniques.
What data structure is used in Lexicographically Smallest String After Reverse?
The core data structure is the string itself. The algorithm relies on index manipulation and substring reversal logic. Two-pointer style access is often used to simulate reversed traversal when comparing characters.
What is the time complexity of Lexicographically Smallest String After Reverse?
The optimized solution runs in O(n^2) time because every pair of indices (l, r) representing a possible substring reversal is evaluated once. Brute force implementations that rebuild the string each time may take O(n^3) time. Space complexity is typically O(n) for storing candidate results.

Ready to solve this problem?

Practice Lexicographically Smallest String After Reverse with our built-in code editor and test cases.

Practice on FleetCode