All problems
1142MediumStringDynamic ProgrammingStack

Tidying a Line of Two Crate Kinds

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1653Minimum Deletions to Make String Balanced

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A line line holds only the characters a and b. The line is tidy when no b stands anywhere before an a, so every a comes before every b.

Return the fewest characters that have to be removed to leave the line tidy.

Examples

Example 1

Input
line = "bab"
Output
1

Removing the single a leaves two b letters, which is tidy. Removing both b letters instead would cost two.

Example 2

Input
line = "bbbaaa"
Output
3

Three b letters stand before three a letters, so either all the a letters or all the b letters have to go, and each costs three.

Example 3

Input
line = "ab"
Output
0

The line is already tidy, so nothing is removed.

Constraints

  • 1 <= line.length <= 10^5
  • every character of line is a or b

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def minimum_deletions(line: str) -> int:
Java
public int minimumDeletions(String line)
September 7
Apply