Minimum Operations to Sort a String Problem
#3863
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3863.
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:
- Sort substring "og" to "go".
- Now, s = "dgo", which is sorted in ascending order. Thus, the answer is 1.
Example 2:
Input: s = "card"
Output: 2
Explanation:
- Sort substring "car" to "acr", so s = "acrd".
- Sort substring "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:
- It is impossible to sort s under the given constraints. Thus, the answer is -1.
Constraints:
1 <= s.length <= 10^5sconsists of only lowercase English letters.
Solution
Approach: Case Analysis
The answer is always 0, 1, 2, 3 or -1.
- Already sorted:
0. - Length 2 and unsorted: the only substrings are single letters, so it is impossible:
-1. - Let
mnandmxbe the smallest and largest letters. If the first letter ismnor the last ismx, sorting everything except that end finishes the job:1. - Otherwise, if
mnormxsits somewhere in the middle, one operation moves it to an end and a second sorts the rest:2. - Otherwise the ends are neither, and the middle holds neither extreme; three operations are needed:
3.
Complexity: O(n) time and O(1) space.
class Solution:
def minOperations(self, s: str) -> int:
if all(a <= b for a, b in zip(s, s[1:])):
return 0
if len(s) == 2:
return -1
mn, mx = min(s), max(s)
if s[0] == mn or s[-1] == mx:
return 1
if any(c in [mn, mx] for c in s[1:-1]):
return 2
return 3