Magicsheet logo

Minimum Deletions to Make String Balanced

Medium
90.1%
Updated 6/1/2025

Minimum Deletions to Make String Balanced

1. What is this problem about?

A string consisting only of 'a's and 'b's is "balanced" if there is no 'a' that comes after a 'b'. This means all 'a's must appear before all 'b's. The Minimum Deletions to Make String Balanced problem asks for the minimum number of character deletions required to make the string balanced.

2. Why is this asked in interviews?

Companies like Meta and Microsoft ask this to evaluate a candidate's ability to process strings in a single pass. The Minimum Deletions to Make String Balanced interview question can be solved using a stack-like logic or prefix/suffix counting. It tests your ability to identify the "conflict" (an 'a' appearing after a 'b') and decide which one to remove greedily.

3. Algorithmic pattern used

The problem can be solved using a Greedy approach with a Stack or a simple counter.

  • Stack Approach: Iterate through the string. If we see an 'a' and the stack top is 'b', we have a conflict. We remove the 'b' (pop) and count 1 deletion. If it's not a conflict, we push 'b's onto the stack. 'a's that are already balanced (before any 'b') are ignored.
  • Counting Approach: Maintain a count of 'b's seen so far. Every time we encounter an 'a' after some 'b's, we have two choices: delete this 'a' or delete one of the previous 'b's. We take the minimum. This "String, Stack, Dynamic Programming interview pattern" is highly efficient (O(N)O(N) time, O(1)O(1) space for the counter version).

4. Example explanation

String: "aababbab".

  1. 'a': Balanced.
  2. 'a': Balanced.
  3. 'b': First 'b', count_b = 1.
  4. 'a': Conflict! Deletions = min(1, count_b). Let's say we delete the 'b'. Deletions = 1, count_b = 0. Wait, a better way to track:
  • 'b' seen: 1 ("aab...")
  • 'a' seen after 'b': 1 ("aaba...") -> delete 'b', total_del = 1, b_count = 0.
  • 'b' seen: 1 ("aabab...")
  • 'b' seen: 2 ("aababb...")
  • 'a' seen after 'b': total_del = min(prev_del + 1, b_count) = min(1+1, 2) = 2. The logic ensures we never have 'ba'.

5. Common mistakes candidates make

In the Minimum Deletions to Make String Balanced coding problem, many candidates overthink the "split point." While you can solve it by checking every possible split point (all 'a's before, all 'b's after), this often leads to O(N2)O(N^2) if not done carefully with prefix sums. Another mistake is not recognizing the stack-based greedy solution, which is much simpler to implement.

6. Interview preparation tip

For "balanced string" problems where certain characters must precede others, think about "what causes the imbalance?" If a 'b' is followed by an 'a', one of them must go. This "Conflict-resolution interview pattern" is a powerful way to frame greedy problems. Practice identifying such triggers in strings.

Similar Questions