Leetcode 1653 Minimum Deletions to Make String Balanced

Minimum Deletions to Make String Balanced

Problem Statement

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

Example 1
  • Input: s = "aababbab"
  • Output: 2
  • Explanation: You can either:
    • Delete the characters at 0-indexed positions 2 and 6 (“aababbab” -> “aaabbb”), or
    • Delete the characters at 0-indexed positions 3 and 6 (“aababbab” -> “aabbbb”).
Example 2
  • Input: s = "bbaaaaabb"
  • Output: 2
  • Explanation: The only solution is to delete the first two characters.

Constraints

  • (1 \leq s.length \leq 10^5)
  • s[i] is ‘a’ or ‘b’.

Solution

class Solution:
    def minimumDeletions(self, s: str) -> int:
        n = len(s)
        prefix_b = 0  # Count of 'b's up to current position
        suffix_a = s.count('a')  # Initial count of 'a's from the start to the end
        result = suffix_a  # Initialize result with the total count of 'a's
        
        for i in range(n):
            if s[i] == 'a':
                suffix_a -= 1  # Decrease suffix_a as we encounter 'a'
            else:
                prefix_b += 1  # Increase prefix_b as we encounter 'b'
            
            # Update the minimum deletions needed at each position
            result = min(result, prefix_b + suffix_a)
        
        return result

Explanation of the Solution

  1. Initialization:

    • prefix_b starts at 0 since no 'b’s have been counted yet.
    • suffix_a is initialized to the total count of 'a’s in the string.
    • result is initialized to the total count of 'a’s because, in the worst case, we might need to delete all 'a’s.
  2. Single Iteration:

    • Iterate through the string once.
    • If the current character is ‘a’, decrement suffix_a since one ‘a’ is being accounted for as we move from left to right.
    • If the current character is ‘b’, increment prefix_b.
    • At each step, update the result with the minimum of the current result and the sum of prefix_b and suffix_a.
  3. Return Result:

    • The result will hold the minimum deletions needed to make the string balanced.

This optimized solution maintains a linear time complexity (O(n)) and requires constant space (O(1)) in addition to the input string.

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值