[Problem description]
Given a string seq consisting only of the characters 'A' and 'B'.
You can repeatedly perform the following operation:
Delete any occurrence of the substring "AB" or "BB".
After deletion, the remaining parts of the string are joined together.
Your task is to determine the minimum possible length of the string after any number of valid deletions.
Note: A substring is a contiguous sequence of characters.
[Example]
Input: seq = "BABBA"
Output: 1
Explanation:
Delete the substring "AB" starting at index 1: "BABBA" -> "BBA"
Delete the substring "BB" starting at index 0: "BBA" -> "A"
No more operations are possible, and the minimum length is 1.
[Constraints]
1 <= length of seq <= 2 * 10^5
[Approach]
This problem can be solved in O(N) time using a stack.
Since "AB" and "BB" can be removed, a 'B' can be eliminated whenever it has an 'A' or another 'B' before it.
We traverse the string seq:
If the character is 'A', push it directly onto the stack.
If the character is 'B':
If the stack is not empty, its top element, whether 'A' or 'B', can pair with this character to form "AB" or "BB" and be removed, so pop the top element.
If the stack is empty, there is no preceding character to pair with this 'B', so it cannot be removed. Push it onto the stack.
After the traversal, the elements remaining in the stack are the characters that cannot be removed. The stack size is the minimum remaining length.
[Code implementation (Python)]
def solution(seq):
stack = []
for char in seq:
if char == 'A':
stack.append('A')
else: # char == 'B'
if stack:
stack.pop()
else:
stack.append('B')
return len(stack)
Discussion
Loading comments…