Minimum Deletions to Make String Balanced

You are given a string `s` made only of the characters `'a'` and `'b'`. The string is balanced when there is no pair of indices `i < j` with `s[i] = 'b'` and `s[j] = 'a'`, that is, every `'a'` comes before every `'b'`. You may delete any number of characters. Return the minimum number of deletions that makes `s` balanced.

30:00

Minimum Deletions to Make String Balanced
medium
Free written solution
Topics
Companies

You are given a string s made only of the characters 'a' and 'b'. The string is balanced when there is no pair of indices i < j with s[i] = 'b' and s[j] = 'a', that is, every 'a' comes before every 'b'. You may delete any number of characters. Return the minimum number of deletions that makes s balanced.

Example 1:
Input: {"s":"aababbab"}
Output: 2
Constraints:
  • 1≤s.length≤1051 \leq s.\text{length} \leq 10^5

  • s[i] is 'a' or 'b'.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"aababbab"}

s: a clashing 'b' and 'a' share a colour

a

0

a

1

b

2

a

3

b

4

b

5

a

6

b

7

Every clash is a 'b' somewhere before an 'a'. Scan left to right, keep the unmatched 'b's on a stack, and cancel one against each 'a' that arrives: each cancelled pair costs exactly one deletion.

pending 'b' stack (0)

empty

deletions (one per clashing pair)

none yet

total 0

Variables
VariableValue
pending_b0
deletions0
DepthFunction Call
Stack empty
0/17