LeetCode 1653, Medium. Topics: String, Dynamic Programming, Stack. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 23 parametrized pytest cases, and a playground notebook:
Problem
You are given a string s consisting only of characters 'a' and 'b'.
You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j] = 'a'.
Return the minimum number of deletions needed to make s balanced.
Examples
Constraints
- 1 <= s.length <= 10^5
- s[i] is ‘a’ or ‘b’.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026