You are given a string s
consisting only of characters ‘0’ and ‘1’. You can apply the following operation any number of times: Choose any two adjacent characters and remove them if they are different (i.e. “01” or “10”). This operation reduces the string’s length by 2. Your task is to return the minimum possible length of the string after performing the operations as many times as possible.
0
by default.The strategy to solve this problem is to simulate the removal operation using a stack-based approach. The basic idea is as follows:
def minLengthAfterRemovals(s: str) -> int:
stack = []
for char in s:
if stack and stack[-1] != char:
stack.pop() # This removes a "01" or "10" pair.
else:
stack.append(char) # Push current character onto stack.
return len(stack)
# Example usage
s = "010101"
print(minLengthAfterRemovals(s)) # Output: 0
The time complexity of this approach is (O(n)), where (n) is the length of the string. This is because we are traversing the string once and each push or pop operation on the stack takes (O(1)) time.
The space complexity is also (O(n)) in the worst case, where no characters are removable, and all characters are stored in the stack.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?