Convert an unbalanced bracket sequence to a balanced sequence
Last Updated :
25 Mar, 2023
Given an unbalanced bracket sequence of ‘(‘ and ‘)’, convert it into a balanced sequence by adding the minimum number of ‘(‘ at the beginning of the string and ‘)’ at the end of the string.
Examples:
Input: str = “)))()”
Output: “((()))()”
Input: str = “())())(())())”
Output: “(((())())(())())”
Method 1:
Approach:
- Initialize an empty stack.
- Iterate over each character in the string.
- If the character is an opening parenthesis, push it onto the stack.
- If the character is a closing parenthesis, pop the most recent opening parenthesis from the stack if it matches the closing parenthesis, or push the closing parenthesis onto the stack if there is no matching opening parenthesis.
- After iterating over all characters, count the remaining unbalanced parentheses on the stack and add the appropriate number of opening and closing parentheses to the beginning and end of the string to balance it.
C++
#include <bits/stdc++.h>
using namespace std;
string balance_parenthesis(string str){
vector< int > st;
for ( auto c: str){
if (c == '(' )
st.push_back(c);
else if (c == ')' )
if (st.size() > 0 && st[st.size() - 1] == '(' )
st.pop_back();
else
st.push_back(c);
}
int closing = 0;
int opening = 0;
for ( int i = 0; i < st.size(); i++){
if (st[i] == '(' ) closing++;
else if (st[i] == ')' )opening++;
}
string res = "" ;
for ( int i = 0; i < opening ; i++)
res = res + '(' ;
res = res + str;
for ( int i = 0; i < closing; i++)
res = res + ')' ;
return res;
}
int main(){
string str = ")))()" ;
cout << "Input:" << endl;
cout << str << endl;
string adjusted_s = balance_parenthesis(str);
cout << "Balanced Parenthesis: " << endl;
cout << adjusted_s << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class Main {
public static String balance_parenthesis(String string){
Stack<Character> stack = new Stack<Character>();
for ( int i = 0 ; i < string.length(); i++){
Character c = string.charAt(i);
if (c == '(' )
stack.push(c);
else if (c == ')' )
if (stack.size() > 0 && stack.peek() == '(' )
stack.pop();
else
stack.push(c);
}
int closing = 0 ;
int opening = 0 ;
while (stack.size() > 0 ){
if (stack.peek() == '(' ) closing++;
else if (stack.peek() == ')' )opening++;
stack.pop();
}
String res = "" ;
for ( int i = 0 ; i < opening ; i++)
res = res + '(' ;
res = res + string;
for ( int i = 0 ; i < closing; i++)
res = res + ')' ;
return res;
}
public static void main(String[] args) {
String string = ")))()" ;
System.out.println( "Input:" );
System.out.println(string);
String adjusted_s = balance_parenthesis(string);
System.out.println( "Balanced Parenthesis: " );
System.out.println(adjusted_s);
}
}
|
Python3
def balance_parenthesis(string):
stack = []
for c in string:
if c = = '(' :
stack.append(c)
elif c = = ')' :
if len (stack) > 0 and stack[ - 1 ] = = '(' :
stack.pop()
else :
stack.append(c)
return '(' * stack.count( ')' ) + string + ')' * stack.count( '(' )
string = ")))()"
print ( "Input:" )
print (string)
adjusted_s = balance_parenthesis(string)
print ( "Balanced Parenthesis: " )
print (adjusted_s)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static string balance_parenthesis( string str)
{
List< char > st = new List< char >();
foreach ( char c in str)
{
if (c == '(' )
st.Add(c);
else if (c == ')' )
if (st.Count > 0 && st[st.Count - 1] == '(' )
st.RemoveAt(st.Count - 1);
else
st.Add(c);
}
int closing = 0;
int opening = 0;
foreach ( char c in st)
{
if (c == '(' )
closing++;
else if (c == ')' )
opening++;
}
string res = "" ;
for ( int i = 0; i < opening; i++)
res += '(' ;
res += str;
for ( int i = 0; i < closing; i++)
res += ')' ;
return res;
}
public static void Main()
{
string str = ")))()" ;
Console.WriteLine( "Input:" );
Console.WriteLine(str);
string adjusted_s = balance_parenthesis(str);
Console.WriteLine( "Balanced Parenthesis:" );
Console.WriteLine(adjusted_s);
}
}
|
Javascript
function balance_parenthesis(string){
let stack = [];
for (let c of string){
if (c == '(' )
stack.push(c)
else if (c == ')' )
if (stack.length > 0 && stack[-1] == '(' )
stack.pop()
else
stack.push(c)
}
let closing = 0;
let opening = 0;
for (let i = 0; i < stack.length; i++){
if (stack[i] == '(' ) closing++;
else if (stack[i] == ')' )opening++;
}
return '(' .repeat(opening-1) + string + ')' .repeat(closing-1)
}
let string = ")))()"
console.log( "Input:" )
console.log(string)
adjusted_s = balance_parenthesis(string)
console.log( "Balanced Parenthesis: " )
console.log(adjusted_s)
|
Output
Input:
)))()
Balanced Parenthesis:
((()))()
Time Complexity: O(n), where n is size of String.
Auxiliary Space: O(1).
Method 2:
Approach:
- Let us assume that whenever we encounter with opening bracket the depth increases by one and with a closing bracket the depth decreases by one.
- Find the maximum negative depth in minDep and add that number of ‘(‘ at the beginning.
- Then loop the new sequence to find the number of ‘)’s needed at the end of the string and add them.
- Finally, return the string.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
string balancedBrackets(string str)
{
int dep = 0;
int minDep = 0;
for ( int i = 0; i < str.length(); i++)
{
if (str[i] == '(' )
dep++;
else
dep--;
if (minDep > dep)
minDep = dep;
}
if (minDep < 0)
{
for ( int i = 0; i < abs (minDep); i++)
str = '(' + str;
}
dep = 0;
for ( int i = 0; i < str.length(); i++)
{
if (str[i] == '(' )
dep++;
else
dep--;
}
if (dep != 0)
{
for ( int i = 0; i < dep; i++)
str = str + ')' ;
}
return str;
}
int main()
{
string str = ")))()" ;
cout << balancedBrackets(str);
}
|
Java
import java.util.*;
class GFG {
static String balancedBrackets(String str)
{
int dep = 0 ;
int minDep = 0 ;
for ( int i = 0 ; i < str.length(); i++)
{
if (str.charAt(i) == '(' )
dep++;
else
dep--;
if (minDep > dep)
minDep = dep;
}
if (minDep < 0 )
{
for ( int i = 0 ; i < Math.abs(minDep); i++)
str = '(' + str;
}
dep = 0 ;
for ( int i = 0 ; i < str.length(); i++)
{
if (str.charAt(i) == '(' )
dep++;
else
dep--;
}
if (dep != 0 )
{
for ( int i = 0 ; i < dep; i++)
str = str + ')' ;
}
return str;
}
public static void main(String[] args)
{
String str = ")))()" ;
System.out.println(balancedBrackets(str));
}
}
|
Python3
def balancedBrackets( Str ):
dep = 0
minDep = 0
for i in Str :
if (i = = '(' ):
dep + = 1
else :
dep - = 1
if (minDep > dep):
minDep = dep
if (minDep < 0 ):
for i in range ( abs (minDep)):
Str = '(' + Str
dep = 0
for i in Str :
if (i = = '(' ):
dep + = 1
else :
dep - = 1
if (dep ! = 0 ):
for i in range (dep):
Str = Str + ')'
return Str
Str = ")))()"
print (balancedBrackets( Str ))
|
C#
using System;
class GFG {
static string balancedBrackets( string str)
{
int dep = 0;
int minDep = 0;
for ( int i = 0; i < str.Length; i++)
{
if (str[i] == '(' )
dep++;
else
dep--;
if (minDep > dep)
minDep = dep;
}
if (minDep < 0)
{
for ( int i = 0; i < Math.Abs(minDep); i++)
str = '(' + str;
}
dep = 0;
for ( int i = 0; i < str.Length; i++)
{
if (str[i] == '(' )
dep++;
else
dep--;
}
if (dep != 0)
{
for ( int i = 0; i < dep; i++)
str = str + ')' ;
}
return str;
}
public static void Main()
{
String str = ")))()" ;
Console.WriteLine(balancedBrackets(str));
}
}
|
Javascript
<script>
function balancedBrackets(str) {
var dep = 0;
var minDep = 0;
for ( var i = 0; i < str.length; i++) {
if (str[i] === "(" ) dep++;
else dep--;
if (minDep > dep) minDep = dep;
}
if (minDep < 0) {
for ( var i = 0; i < Math.abs(minDep); i++) str = "(" + str;
}
dep = 0;
for ( var i = 0; i < str.length; i++) {
if (str[i] === "(" ) dep++;
else dep--;
}
if (dep !== 0) {
for ( var i = 0; i < dep; i++) str = str + ")" ;
}
return str;
}
var str = ")))()" ;
document.write(balancedBrackets(str));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...