Watch 7 video solutions for Minimum Operations to Sort a String, a medium level problem involving String. This walkthrough by CodeWithMeGuys has 626 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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.
| 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 |