Minimum Deletions to Make String Balanced — LeetCode 1653 Python Solution

MediumStackStringDynamic Programming
Problem
#1653
Pattern
Stack
Reading time
2 min

The 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.

Example

Input
s = "aababbab"
Output
2
Explanation
You can either:

Python solution

Python
class Solution:
    def minimumDeletions(self, s: str) -> int:
        n = len(s)
        f = [0] * (n + 1)
        b = 0
        for i, c in enumerate(s, 1):
            if c == 'b':
                f[i] = f[i - 1]
                b += 1
            else:
                f[i] = min(f[i - 1] + 1, b)
        return f[n]

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1653. Minimum Deletions to Make String Balanced is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1653. Minimum Deletions to Make String Balanced?
LeetCode 1653. Minimum Deletions to Make String Balanced is rated Medium on LeetCode.
What is the time complexity of LeetCode 1653. Minimum Deletions to Make String Balanced?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 1653. Minimum Deletions to Make String Balanced?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1653. Minimum Deletions to Make String Balanced cover?
LeetCode 1653. Minimum Deletions to Make String Balanced is tagged Stack, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview