#1653
Minimum Deletions to Make String Balanced
MediumStringDynamic ProgrammingStackTwo PointersGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages a single pass through the string to count the number of 'b's before each 'a' and calculates the minimum deletions needed in a more efficient manner. This approach is faster and scales better with larger strings.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two counters: one for the count of 'b's seen so far and another for the total deletions needed.
- 2Step 2: Traverse the string from left to right. For each character: - If it's 'b', increment the count of 'b's. - If it's 'a', add the count of 'b's to the deletions needed.
- 3Step 3: The final count of deletions will give the minimum deletions needed to make the string balanced.
solution.py14 lines
1# Full working Python code
2
3def min_deletions_optimal(s):
4 b_count = 0
5 deletions = 0
6 for char in s:
7 if char == 'b':
8 b_count += 1
9 elif char == 'a':
10 deletions += b_count
11 return deletions
12
13# Example usage:
14print(min_deletions_optimal('aababbab')) # Output: 2ℹ
Complexity note: The time complexity is O(n) because we make a single pass through the string. The space complexity is O(1) since we only use a constant amount of space for counters.
- 1The order of characters matters; 'b's must always come before 'a's to maintain balance.
- 2Counting occurrences of 'b's before each 'a' helps determine the necessary deletions efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.