#3863

Minimum Operations to Sort a String

Medium
StringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

We can determine the minimum operations by checking the positions of the minimum and maximum characters in the string. If they are in the correct positions, we can sort the string in fewer operations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the string is already sorted; if yes, return 0.
  2. 2Step 2: Identify the minimum character (mn) and maximum character (mx) in the string.
  3. 3Step 3: If mn is at the start or mx is at the end (not the entire string), return 1; otherwise, return 2.
solution.py7 lines
1def minOperations(s):
2    if s == ''.join(sorted(s)):
3        return 0
4    mn, mx = min(s), max(s)
5    if s[0] == mn or s[-1] == mx:
6        return 1
7    return 2

Complexity note: This complexity arises from scanning the string to find min and max characters, which is O(n).

  • 1Identifying the positions of min and max characters is crucial.
  • 2Sorting substrings can often be reduced to checking boundary conditions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.