Lexicographically Smallest String After Reverse II
You are given a string s of length n consisting only of lowercase English letters.
You must perform exactly one operation. In this operation, choose an integer k such that 1 ≤ k ≤ n, and perform one of the following:
- Reverse the first k characters, or
- Reverse the last k characters
Return the lexicographically smallest string that can be obtained after performing exactly one operation.
A string a is lexicographically smaller than string b if at the first position where they differ, a has a smaller character than b.
Example 1:
Input: s = "cbad"
Output: "abcd"
Explanation:
Choose k = 4 and reverse the entire string. "cbad" → "dabc"
Now choose k = 3 and reverse the first 3 characters. "cba" → "abc
Resulting string becomes "abcd", which is the lexicographically smallest possible after exactly one operation
Example 2:
Input: s = "bdca"
Output: "acdb"
Explanation:
Choose k = 4 and reverse the entire string. "bdca" → "acdb"
This gives the smallest possible string achievable using one valid operation.
Now Your Turn!
Pick the correct output for the given inputInput: s = "bacd"
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 ≤ n = s.length ≤ 105
- s consists only of lowercase English letters ('a' to 'z').
- Exactly one operation must be performed.
- The chosen k must satisfy 1 ≤ k ≤ n.