![]() |
VOOZH | about |
Given a string S of size N consisting of '(', ')', and '$', the task is to check whether the given string can be converted into a balanced bracket sequence by replacing every occurrence of $ with either ) or (.
A balanced bracket sequence is a sequence where every opening bracket "(" has a corresponding closing bracket ")".
Examples:
Input: S = "()($"
Output: Yes
Explanation: Convert the string into a balanced bracket sequence: ()().Input: S = "$()$("
Output: No
Explanation: Possible replacements are "(((((", "(())(", ")(()(", ")()((", none of which are balanced. Hence, a balanced bracket sequence can not be obtained.
Approach: The above problem can be solved by using a Stack. The idea is to check if all ) can be balanced with ( or $ and vice versa. Follow the steps below to solve this problem:
Below is the implementation of the above approach:
Yes
Time Complexity: O(N)
Auxiliary Space: O(N)