Loading Similar Posts
Problem Statement:
Given a dataset of strings containing only parentheses, characters '(' and ')', the data represented by the string is valid if it is a balanced bracket sequence.One adjustment to the string can be made: at most one bracket can be moved from its original place to any other position in the string. The task is to determine whether, for each string, it is possible to balance the bracket sequence in 1 move or less. Return an array of the size of the dataset, where the i^th integer is 1 if the string can be converted into a balanced string, and 0 otherwise.
Note: A string s is a balanced bracket sequence if:
Example:
n = 3
dataset = [")(", "(()", "()"]
Hence, the answer is [1, 0, 1].
Problem1 (Convertible Balanced Bracket Sequence) Solution
Overview
Think of a situation where you don't look at the whole string, but just the "broken" parts. If you simply pair up all the valid
()brackets as you read them and pretend they don't exist, what are you left with?You will always be left with some closing brackets followed by opening ones, like
)...(. Because moving exactly one bracket can only fix at most one misplaced)and one misplaced(, our leftover "broken" pile can have at most one of each to be fixable!Approach
1. Cancel the Good Pairs
We can iterate through the string and keep track of unmatched opening brackets
(. Whenever we see a closing bracket), we check if we have a(available to pair it with. If we do, we cancel them out! If we don't, we count it as an unmatched closing bracket.2. Check the Leftovers
After looping through the entire string, we just look at what is left.
If we have
0unmatched brackets, it was already balanced (0 moves).If we have exactly
1unmatched open and1unmatched close (like)(), we can fix it by moving one of them (1 move).Any more than that (like
))((), and 1 move won't be enough to save it!Implementation-:
Time Complexity
Time: O(N) - We only need to iterate through the string of brackets exactly once.
Space: O(1) - We don't even need a real Stack! We can just use two integer variables to keep count of the unmatched brackets.