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 <= 105s[i] is 'a' or 'b'.This approach involves using prefix sums to count the number of 'b's seen until each index and adjusting to track the potential number of deletions to ensure a balanced string.
This C solution iterates through the string once to count total 'b's. Then it iteratively calculates the minimum deletions needed by adjusting counts of 'a' seen and remaining 'b's using a greedy approach.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), since we're using constant space.
Minimum Number of Swaps to Make String Balanced - Leetcode 1963 Weekly Contest - Python • NeetCode • 47,493 views views
Watch 9 more video solutions →Practice Minimum Deletions to Make String Balanced with our built-in code editor and test cases.
Practice on FleetCode