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:
C++
#include <bits/stdc++.h>
using namespace std;
bool canBeBalanced(string sequence)
{
if (sequence.size() % 2)
return false ;
stack< char > stack_, stack2_;
int countOpen = 0, countClosed = 0;
int countSymbol = 0;
for ( int i = 0;
i < sequence.size(); i++) {
if (sequence[i] == ')' ) {
countClosed++;
if (stack_.empty()) {
return false ;
}
else {
stack_.pop();
}
}
else {
if (sequence[i] == '$' ) {
countSymbol++;
}
else {
countOpen++;
}
stack_.push(sequence[i]);
}
}
for ( int i = sequence.size() - 1;
i >= 0; i--) {
if (sequence[i] == '(' ) {
if (stack2_.empty()) {
return false ;
}
else {
stack2_.pop();
}
}
else {
stack2_.push(sequence[i]);
}
}
int extra = abs (countClosed - countOpen);
if (countSymbol < extra) {
return false ;
}
else {
countSymbol -= extra;
if (countSymbol % 2 == 0) {
return true ;
}
}
return false ;
}
int main()
{
string S = "()($" ;
if (canBeBalanced(S)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean canBeBalanced(String sequence)
{
if (sequence.length() % 2 == 1 )
return false ;
Stack<Character> stack_ = new Stack<Character>();
Stack<Character> stack2_ = new Stack<Character>();
int countOpen = 0 , countClosed = 0 ;
int countSymbol = 0 ;
for ( int i = 0 ;
i < sequence.length(); i++)
{
if (sequence.charAt(i) == ')' )
{
countClosed++;
if (stack_.isEmpty())
{
return false ;
}
else
{
stack_.pop();
}
}
else
{
if (sequence.charAt(i) == '$' )
{
countSymbol++;
}
else
{
countOpen++;
}
stack_.add(sequence.charAt(i));
}
}
for ( int i = sequence.length() - 1 ;
i >= 0 ; i--)
{
if (sequence.charAt(i) == '(' )
{
if (stack2_.isEmpty())
{
return false ;
}
else
{
stack2_.pop();
}
}
else
{
stack2_.add(sequence.charAt(i));
}
}
int extra = Math.abs(countClosed - countOpen);
if (countSymbol < extra)
{
return false ;
}
else
{
countSymbol -= extra;
if (countSymbol % 2 == 0 )
{
return true ;
}
}
return false ;
}
public static void main(String[] args)
{
String S = "()($" ;
if (canBeBalanced(S))
{
System.out.print( "Yes" );
}
else
{
System.out.print( "No" );
}
}
}
|
Python3
def canBeBalanced(sequence):
if ( len (sequence) % 2 ):
return False
stack_, stack2_ = [], []
countOpen ,countClosed = 0 , 0
countSymbol = 0
for i in range ( len (sequence)):
if (sequence[i] = = ')' ):
countClosed + = 1
if ( len (stack_) = = 0 ):
return False
else :
del stack_[ - 1 ]
else :
if (sequence[i] = = '$' ):
countSymbol + = 1
else :
countOpen + = 1
stack_.append(sequence[i])
for i in range ( len (sequence) - 1 , - 1 , - 1 ):
if (sequence[i] = = '(' ):
if ( len (stack2_) = = 0 ):
return False
else :
del stack2_[ - 1 ]
else :
stack2_.append(sequence[i])
extra = abs (countClosed - countOpen)
if (countSymbol < extra):
return False
else :
countSymbol - = extra
if (countSymbol % 2 = = 0 ) :
return True
return False
if __name__ = = '__main__' :
S = "()($"
if (canBeBalanced(S)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool canBeBalanced(String sequence)
{
if (sequence.Length % 2 == 1)
return false ;
Stack< char > stack_ = new Stack< char >();
Stack< char > stack2_ = new Stack< char >();
int countOpen = 0, countClosed = 0;
int countSymbol = 0;
for ( int i = 0;
i < sequence.Length; i++)
{
if (sequence[i] == ')' )
{
countClosed++;
if (stack_.Count==0)
{
return false ;
}
else
{
stack_.Pop();
}
}
else
{
if (sequence[i] == '$' )
{
countSymbol++;
}
else
{
countOpen++;
}
stack_.Push(sequence[i]);
}
}
for ( int i = sequence.Length - 1;
i >= 0; i--)
{
if (sequence[i] == '(' )
{
if (stack2_.Count == 0)
{
return false ;
}
else
{
stack2_.Pop();
}
}
else
{
stack2_.Push(sequence[i]);
}
}
int extra = Math.Abs(countClosed - countOpen);
if (countSymbol < extra)
{
return false ;
}
else
{
countSymbol -= extra;
if (countSymbol % 2 == 0)
{
return true ;
}
}
return false ;
}
public static void Main(String[] args)
{
String S = "()($" ;
if (canBeBalanced(S))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
}
|
Javascript
<script>
function canBeBalanced(sequence)
{
if (sequence.length % 2 == 1)
return false ;
let stack_ = [];
let stack2_ = [];
let countOpen = 0, countClosed = 0;
let countSymbol = 0;
for (let i = 0;
i < sequence.length; i++)
{
if (sequence[i] == ')' )
{
countClosed++;
if (stack_.length==0)
{
return false ;
}
else
{
stack_.pop();
}
}
else
{
if (sequence[i] == '$' )
{
countSymbol++;
}
else
{
countOpen++;
}
stack_.push(sequence[i]);
}
}
for (let i = sequence.length - 1;
i >= 0; i--)
{
if (sequence[i] == '(' )
{
if (stack2_.length==0)
{
return false ;
}
else
{
stack2_.pop();
}
}
else
{
stack2_.push(sequence[i]);
}
}
let extra = Math.abs(countClosed - countOpen);
if (countSymbol < extra)
{
return false ;
}
else
{
countSymbol -= extra;
if (countSymbol % 2 == 0)
{
return true ;
}
}
return false ;
}
let S = "()($" ;
if (canBeBalanced(S))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)