You are given a string s consisting of lowercase English letters.
In one operation, you can select any substring of s that is not the entire string and sort it in non-descending alphabetical order.
Return the minimum number of operations required to make s sorted in non-descending order. If it is not possible, return -1.
Example 1:
Input: s = "dog"
Output: 1
Explanation:
"og" to "go".s = "dgo", which is sorted in ascending order. Thus, the answer is 1.Example 2:
Input: s = "card"
Output: 2
Explanation:
"car" to "acr", so s = "acrd"."rd" to "dr", making s = "acdr", which is sorted in ascending order. Thus, the answer is 2.Example 3:
Input: s = "gf"
Output: -1
Explanation:
s under the given constraints. Thus, the answer is -1.
Constraints:
1 <= s.length <= 105s consists of only lowercase English letters.Problem Overview: You are given a string and need to determine the minimum number of operations required to transform it into its lexicographically sorted version. The challenge is identifying where characters violate sorted order and determining the smallest set of operations needed to fix those positions efficiently.
Approach 1: Brute Force Simulation (O(n^2) time, O(n) space)
The most direct idea is to simulate how the string becomes sorted. First generate the sorted target string. Then repeatedly scan the current string and move or adjust characters that are out of place until it matches the target. Each operation fixes one misplaced region, but finding the correct character and shifting elements may require scanning the string repeatedly. Because each correction can take O(n) time and you may perform up to O(n) corrections, the total time complexity grows to O(n^2) with O(n) space for temporary strings. This approach helps build intuition but becomes slow for large inputs.
Approach 2: Case Analysis with Target Comparison (O(n log n) time, O(n) space)
A more efficient strategy compares the original string with its sorted version and analyzes where characters diverge. Start by creating a sorted copy of the string using a standard sorting routine. Then iterate through both strings simultaneously. Whenever the current character already matches the sorted position, no operation is needed. When it doesn't, you analyze the mismatch segment and determine how many operations are required to realign those characters with the sorted order.
The key insight: sorting defines the exact final arrangement. Instead of performing actual modifications, you only count structural mismatches between the original and sorted strings. This turns the problem into a counting and case analysis task. A single pass through the string identifies contiguous mismatched regions and increments the operation counter accordingly.
This approach uses basic string traversal combined with reasoning about sorted order. Sorting the string costs O(n log n), while the comparison scan runs in O(n). Space complexity is O(n) because the sorted copy must be stored.
Recommended for interviews: The case analysis approach is what interviewers typically expect. Brute force simulation demonstrates understanding of the transformation process, but comparing the string against its sorted version shows stronger algorithmic reasoning. It also highlights your ability to reduce a modification problem into a simpler counting problem using properties of strings and ordering logic often seen in greedy-style reasoning.
We first check whether the string is already sorted in ascending order; if so, return 0.
Otherwise, if the string has length 2, since we cannot choose the entire string to sort, it is impossible to sort the string, so we return -1.
Next, we find the minimum character mn and the maximum character mx in the string. If the first character of the string equals mn, or the last character equals mx, then one operation on the remaining substring is sufficient to sort the entire string, so we return 1.
Otherwise, if some character in the middle of the string equals mn or mx, we need one operation to move that character to the beginning or the end of the string, and then one more operation to sort the rest, so we return 2.
Finally, if none of the above cases apply, we need one operation on the substring containing both mn and mx, followed by one more operation on the remaining substring, so we return 3.
The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).
Python
Java
C++
Go
TypeScript
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Simulation | O(n^2) | O(n) | Useful for understanding the transformation process or when constraints are very small |
| Case Analysis with Sorted Target | O(n log n) | O(n) | General case solution; efficient and straightforward for interview settings |
Leetcode 3863 | Minimum Operations to Sort a String | Leetcode weekly contest 492 • CodeWithMeGuys • 626 views views
Watch 6 more video solutions →Practice Minimum Operations to Sort a String with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor