Ctrl K

a's Then b's With the Fewest Deletions

Medium
The string line contains only the letters a and b. We want no b to appear to the left of any a, so that the string reads "all the as, then all the bs" (either part may be empty). The only thing you may do is delete characters; the rest keep their order. Return the smallest number of deletions that brings the string into that shape.
Example 1
line="babab" → 2

Delete the first two bs to get aab, or delete both as to get bbb. Either way two deletions are enough, and one is not.

Example 2
line="aabba" → 1

Removing the last a is enough: aabb remains.

Example 3
line="aaabbb" → 0

The string is already in order, so nothing has to go.

Constraints
  • 1 ≤ len(line) ≤ 10⁵
  • every character of line is a or b
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBrackets With Wildcards MediumFill In to Repeated abc MediumLongest Balanced Bracket Stretch HardClear the Marble Row HardFlip the Circuit Output Hard
loading Python…
Input
line="babab"
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 193 tests on the server, hidden ones included.