Minimum Deletions to Make String Balanced

Medium Topics Company Tags

Delete as few characters as possible from s so that every remaining a comes before every remaining b. Either letter may be absent from the result. Return the minimum number of deletions; the relative order of characters you keep cannot change.

Example 1:

Input: s = "a"

Output: 0

Explanation: A string containing only "a" is already balanced.

Example 2:

Input: s = "b"

Output: 0

Explanation: A string containing only "b" is already balanced.

Example 3:

Input: s = "ba"

Output: 1

Explanation: The "b" occurs before an "a", so one deletion is necessary. Removing either character leaves a balanced string.

Constraints:

  • 1 <= s.length <= 100000
  • Each character is a or b.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.