Minimum Deletions to Make String Balanced Problem
#1653
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 1653.
You are given a string s consisting only of characters 'a' and 'b'.
You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.
Return the minimum number of deletions needed to make s balanced.
Example 1:
Input: s = "aababbab"
Output: 2
Explanation: You can either:
Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or
Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").
Example 2:
Input: s = "bbaaaaabb"
Output: 2
Explanation: The only solution is to delete the first two characters.
Constraints:
1 <= s.length <= 10^5s[i]is'a'or'b'.
Solution
Approach: Dynamic Programming
Let f[i] be the fewest deletions that make the first i characters balanced, with f[0] = 0, and let b count the 'b's seen so far.
- If
s[i-1]is'b', appending it to a balanced prefix keeps it balanced:f[i] = f[i-1], andbgrows by one. - If
s[i-1]is'a', either delete this'a'(f[i-1] + 1) or keep it and delete every'b'before it (b). Sof[i] = min(f[i-1] + 1, b).
The answer is f[n]. Each step only uses f[i-1], so a single variable could replace the array.
Complexity: O(n) time and O(n) space (or O(1) with a single variable), where n is the length of s.
class Solution:
def minimumDeletions(self, s: str) -> int:
n = len(s)
f = [0] * (n + 1)
b = 0
for i, c in enumerate(s, 1):
if c == 'b':
f[i] = f[i - 1]
b += 1
else:
f[i] = min(f[i - 1] + 1, b)
return f[n]