#1830
Minimum Number of Operations to Make String Sorted
HardHash TableMathStringCombinatoricsCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages combinatorial counting to determine the number of operations needed to sort the string without simulating each step. This approach is faster and avoids unnecessary iterations.
⚙️
Algorithm
4 steps- 1Step 1: Count the frequency of each character in the string.
- 2Step 2: For each character, calculate how many characters are smaller than it that come after it in the string.
- 3Step 3: Use the counts to determine the number of swaps needed to sort the string.
- 4Step 4: Return the total number of operations modulo 10^9 + 7.
solution.py13 lines
1def min_operations(s):
2 MOD = 10**9 + 7
3 count = [0] * 26
4 for char in s:
5 count[ord(char) - ord('a')] += 1
6 operations = 0
7 total = 0
8 for char in s:
9 index = ord(char) - ord('a')
10 total += sum(count[:index])
11 operations += total
12 count[index] -= 1
13 return operations % MODℹ
Complexity note: The complexity is O(n) because we only traverse the string a couple of times and use a fixed-size array for counting characters.
- 1The problem can be viewed as counting inversions in the string.
- 2Understanding character frequency can help optimize the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.