VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-given-string-can-be-converted-to-a-balanced-bracket-sequence/

⇱ Check if a given string can be converted to a Balanced Bracket Sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a given string can be converted to a Balanced Bracket Sequence

Last Updated : 23 Jul, 2025

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:

  • Store the frequency of "(", ")" and "$" in variables like countOpen, countClosed, and countSymbol respectively.
  • Initialize a variable ans as 1 to store the required result and a stack stack_1 to check if all ")" can be balanced with "(" or $.
  • Traverse the string S using the variable i and do the following:
  • Reverse the string S, and follow the same procedure to check if all "(" can be balanced with ")" or "$".
  • If the value of countSymbol is less than the absolute difference of countOpen and countClosed then set ans to 0. Else balance the extra parenthesis with the symbols. After balancing if countSymbol is odd, set ans as 0.
  • After the above steps, print the value of ans as the result.

Below is the implementation of the above approach:


Output: 
Yes

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment