Taro Logo

Minimum Deletions to Make String Balanced

#2 Most AskedMedium
Topics:
StringsDynamic Programming

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 <= 105
  • s[i] is 'a' or 'b'​​.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the input string $s$ we can expect?
  2. Are there any characters in the string other than 'a' and 'b', such as uppercase letters or whitespace, or is the alphabet strictly limited to 'a' and 'b'?
  3. How should we handle edge cases like an empty string or a string that is already fully balanced?
  4. Is the minimum number of deletions guaranteed to fit within a standard 32-bit integer, or could the input be large enough to require 64-bit integers?
  5. Are we guaranteed that the input string will only contain valid characters, or should I write validation logic for invalid inputs?

Brute Force Solution

Approach

Imagine you have a row of items of two different types, and your goal is to remove some items so that all items of the first type appear before any items of the second type. The brute force strategy involves testing every single spot where you could possibly draw a dividing line and checking how many items you would need to throw away to make everything correct for that specific division.

Here's how the algorithm would work step-by-step:

  1. Pretend you are placing a dividing wall somewhere along the row of items, testing every possible spot from the very beginning to the very end.
  2. For each spot you place the wall, look at everything to the left of the wall.
  3. Count how many items of the second type are incorrectly sitting on that left side, because any item of the second type on the left will need to be deleted.
  4. Next, look at everything to the right of the wall.
  5. Count how many items of the first type are incorrectly sitting on that right side, because any item of the first type on the right will also need to be deleted.
  6. Add up the items you counted from both sides to find the total number of deletions required for this specific wall placement.
  7. Move the wall one spot over and repeat the counting process for this new position.
  8. Continue doing this for every possible dividing spot until you have tried them all.
  9. Compare the total deletions from every attempt and pick the lowest number you found.

Code Implementation

def minimum_deletions(input_string):
    minimum_deletions_found = len(input_string)
    
    # Test every possible dividing wall position from before the first character to after the last
    for wall_position in range(len(input_string) + 1):
        current_deletions = 0
        
        # Count incorrect 'b' characters on the left side of our imaginary dividing wall
        for left_index in range(wall_position):
            if input_string[left_index] == 'b':
                current_deletions += 1
                
        # Count incorrect 'a' characters on the right side of our imaginary dividing wall
        for right_index in range(wall_position, len(input_string)):
            if input_string[right_index] == 'a':
                current_deletions += 1
                
        # Track the lowest deletion count found across all tested wall positions
        if current_deletions < minimum_deletions_found:
            minimum_deletions_found = current_deletions
            
    return minimum_deletions_found

Big(O) Analysis

Time Complexity
O(n²) – Given a string of length n, the brute force strategy places a dividing wall at each of the n possible split positions. For every single wall placement, the algorithm iterates across the entire string to count misplaced elements on both the left and right sides. This nested process requires scanning approximately n elements for each of the n possible wall positions, resulting in roughly n * n/2 total operations. Simplifying this expression by dropping the constant factor yields a final time complexity of O(n²).
Space Complexity
O(1) – The brute force strategy described only requires a few primitive integer variables to keep track of the wall placement, counts of misplaced items, and the minimum deletions found so far. No auxiliary data structures, lists, or recursive calls scaling with the input size N are used. Therefore, the extra memory remains completely constant regardless of how large the input string is.

Optimal Solution

Approach

To make the string balanced, we need to ensure that no special first-type character appears after any second-type character. The optimal approach walks through the sequence while keeping a running tally of how many misfits we would need to remove to keep everything in order.

Here's how the algorithm would work step-by-step:

  1. Imagine walking along the string from the very beginning to the very end while carrying a mental counter for the misfits you encounter.
  2. Every time you spot a second-type character, note it down because it might need to be removed if a first-type character appears later.
  3. Every time you spot a first-type character, check if you have previously noted any second-type characters. If you have, you face a choice: either remove the previous second-type character or remove the current first-type character.
  4. Keep a running total of the minimum removals needed as you make your way across the entire string.
  5. Whenever your running total dips below zero, it means you have seen more first-type characters than necessary, so simply reset your tally and keep moving forward.
  6. By the time you reach the end of the string, your running tally will reveal the exact minimum number of deletions required to achieve perfect balance.

Code Implementation

def minimum_deletions(input_string):
    # Track invalid 'b' characters that disrupt the balanced order of 'a's and 'b's.
    second_type_count = 0
    
    minimum_deletions_needed = 0
    
    for current_character in input_string:
        if current_character == 'b':
            second_type_count += 1
        else:
            # Encountering 'a' after 'b' forces a choice to remove one of them.
            if second_type_count > 0:
                second_type_count -= 1
                minimum_deletions_needed += 1
            
            # Reset tally when surplus 'a' characters make prior deletions obsolete.
            if minimum_deletions_needed < 0:
                minimum_deletions_needed = 0
                
    return minimum_deletions_needed

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single pass through the input string of size n, where we iterate character by character from the beginning to the end. During this traversal, constant time operations are performed for each character, such as updating our running tally of misfits and adjusting the minimum deletions count. Since we only visit each character once and maintain a running total without nested loops or repeated scans, the total operations scale linearly with n. This results in approximately n operations, which simplifies to the final Big O time complexity of O(n).
Space Complexity
O(1) – The algorithm only maintains a few primitive scalar variables to hold the running tally of misfits and the minimum removals, without allocating any auxiliary data structures or recursive calls. Because these few scalar variables require a constant amount of memory regardless of the input size, the extra space usage remains strictly independent of N. As the input string length N grows, the memory footprint does not scale, resulting in constant auxiliary space.

Edge Cases

String of length zero or one
How to Handle:
The algorithm naturally processes these without error and correctly returns zero since no violations can exist.
String already completely balanced
How to Handle:
The counting logic will never encounter an 'a' after a 'b', resulting in zero deletions.
String with all identical characters such as all 'a's or all 'b's
How to Handle:
The algorithm tallies the characters correctly and determines that zero deletions are required.
String in completely reverse order such as all 'b's followed by all 'a's
How to Handle:
The greedy approach correctly counts the misplaced characters and removes either all 'a's or all 'b's.
Extremely large strings up to the maximum constraints
How to Handle:
An optimal linear scan approach processes the string in O(n) time and O(1) space, avoiding performance and memory bottlenecks.
Alternating characters like abababab
How to Handle:
The stack or count tracking efficiently computes the optimal subset of deletions to maintain balance.
0/9 completed