Minimum Deletions to Make String Balanced (LeetCode 1653): Solution and Explanation

Medium
String
Dynamic programming
Stack

A string of as and bs is balanced when no b comes before an a. Return the fewest deletions that make it balanced. For aababbab the answer is 2.

Intuition

A balanced string looks like aaa...bbb. The only thing wrong with any other string is a b that sits somewhere before an a. Call that pair a clash.

Every clash needs at least one of its two characters deleted. If we can find k clashes that share no characters, we need at least k deletions.

Scan left to right and keep the bs that are not paired yet, like a stack. When an a arrives and a b is waiting, pair them. This greedy pairing finds as many disjoint clashes as possible, and that number of deletions is also enough: it equals the cost of the best split into an a part and a b part.

Approach: Stack of pending b's

  1. Keep pendingB = 0 (the size of a stack of unpaired bs) and deletions = 0.
  2. For each character: if it is b, push it by adding one to pendingB.
  3. If it is a and pendingB > 0, pop one b and add one to deletions: this a and that b clash.
  4. An a with no pending b is already in the right place, so skip it.
  5. Return deletions.

Step-by-step example

s = "aababbab"
  1. Indices 0 and 1 are a with no pending b: nothing to do.
  2. Index 2 is b: push it. Pending 1.
  3. Index 3 is a: it clashes with the b at index 2. Pop it, deletions 1. Pending 0.
  4. Indices 4 and 5 are b: push both. Pending 2.
  5. Index 6 is a: it clashes with the b at index 5. Pop it, deletions 2. Pending 1.
  6. Index 7 is b: push it. The scan ends with 2 deletions, the answer.

Code: Python, Java, C++

1class Solution:
2    def minimumDeletions(self, s: str) -> int:
3        pending_b = 0
4        deletions = 0
5        for ch in s:
6            if ch == 'b':
7                pending_b += 1
8            elif pending_b > 0:
9                pending_b -= 1
10                deletions += 1
11        return deletions
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the string with constant work per character.

Space

O(1)

The stack only ever holds bs, so its size is all we need to store.

Other approaches

Dynamic programming over the prefix (time O(n), space O(1))

Let dp be the answer for the prefix read so far and bCount the number of bs in it. On b, dp stays the same. On a, either delete this a (dp + 1) or delete every earlier b (bCount), so dp = min(dp + 1, bCount).

Try every split point (time O(n), space O(n))

For each split k, delete the bs left of k and the as right of k. With prefix counts of b and suffix counts of a this is linear too, but needs two arrays.

Common mistakes

  • Counting every (b, a) index pair instead of disjoint pairs. In bbaa there are four clashing pairs but only two deletions are needed.
  • Counting all bs before the last a, which over-deletes when deleting a few as would be cheaper, as in bbbba.
  • Forgetting that an empty or one-character string is already balanced, so the answer can be 0.

Frequently asked questions

Why is the greedy pairing optimal?

Each pair it forms is a clash, and pairs share no characters, so at least that many deletions are needed. The pair count also equals the cheapest split point (delete the bs left of it and the as right of it), which is the same value the dynamic programming alternative computes, so the bound is reached.

How is this like valid parentheses?

Read b as an opening bracket and a as a closing one. Each matched bracket pair is one clash, and the answer is the number of matched pairs.

Which characters should actually be deleted?

Pick the split point that minimises the bs on its left plus the as on its right, and delete exactly those. The question only asks for the count, and the stack gives it without tracking positions.