Minimum operation required to make a balanced sequence
Last Updated :
12 Sep, 2022
A balanced sequence is defined as a string in which for every opening bracket there are 2 continuous closing brackets. Thus, {}}, {{}}}}, {{}}{}}}} are balanced, whereas }}{, {} are not balanced.
Now given a sequence of brackets (‘{‘ and ‘}’), and you can perform only one operation on that sequence, i.e., either insert an opening or closing bracket at any position. You have to tell the minimum number of operations required to make the given sequence balanced.
Input: str = “{}}”
Output: 0
The sequence is already balanced.
Input: str = “{}{}}}”
Output: 3
The updated sequence will be “{}}{}}{}}”.
Approach: For making a balanced sequence, two continuous closing brackets are required for every opening bracket. There can be 3 cases:
- When the current character is an opening bracket: If the previous character is not a closing bracket, then simply insert the opening bracket to stack, else there is a need for a closing bracket that will cost one operation.
- If the stack is empty and the current character is a closing bracket: In this case, one opening bracket is required that will cost one operation and insert that opening bracket to the stack.
- If the stack is not empty but the current character is a closing bracket: Here, only the count of closing brackets is required. If it is 2, then remove one opening bracket from the stack, else increment the count of the closing bracket.
At the end of the string, if the stack is not empty, then the required count of closing brackets will be ((2 * size of the stack) – current count of closing brackets).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minOperations(string s, int len)
{
int operationCnt = 0;
stack< char > st;
int cntClosing = 0;
for ( int i = 0; i < len; i++) {
if (s[i] == '{' ) {
if (cntClosing > 0) {
operationCnt++;
st.pop();
}
st.push(s[i]);
cntClosing = 0;
}
else if (st.empty()) {
st.push( '{' );
operationCnt++;
cntClosing = 1;
}
else {
cntClosing = (cntClosing + 1) % 2;
if (cntClosing == 0) {
st.pop();
}
}
}
operationCnt += st.size() * 2 - cntClosing;
return operationCnt;
}
int main()
{
string str = "}}{" ;
int len = str.length();
cout << minOperations(str, len);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int minOperations(String s, int len)
{
int operationCnt = 0 ;
Stack<Character> st = new Stack<Character>();
int cntClosing = 0 ;
for ( int i = 0 ; i < len; i++)
{
if (s.charAt(i) == '{' )
{
if (cntClosing > 0 )
{
operationCnt++;
st.pop();
}
st.add(s.charAt(i));
cntClosing = 0 ;
}
else if (st.isEmpty())
{
st.add( '{' );
operationCnt++;
cntClosing = 1 ;
}
else
{
cntClosing = (cntClosing + 1 ) % 2 ;
if (cntClosing == 0 )
{
st.pop();
}
}
}
operationCnt += st.size() * 2 - cntClosing;
return operationCnt;
}
public static void main(String[] args)
{
String str = "}}{" ;
int len = str.length();
System.out.print(minOperations(str, len));
}
}
|
Python3
def minOperations(s, length):
operationCnt = 0
stack = []
cntClosing = 0
for i in range ( 0 , length):
if (s[i] = = '{' ):
if (cntClosing > 0 ):
operationCnt + = 1
stack.pop()
stack.append(s[i])
cntClosing = 0
elif not stack:
stack.append( '{' )
operationCnt + = 1
cntClosing = 1
else :
cntClosing = (cntClosing + 1 ) % 2
if (cntClosing = = 0 ):
stack.pop()
operationCnt + = len (stack) * 2 - cntClosing
return operationCnt
if __name__ = = '__main__' :
string = "}}{"
print (minOperations(string, len (string)))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int minOperations(String s,
int len)
{
int operationCnt = 0;
Stack< char > st = new Stack< char >();
int cntClosing = 0;
for ( int i = 0; i < len; i++)
{
if (s[i] == '{' )
{
if (cntClosing > 0)
{
operationCnt++;
st.Pop();
}
st.Push(s[i]);
cntClosing = 0;
}
else if (st.Count != 0)
{
st.Push( '{' );
operationCnt++;
cntClosing = 1;
}
else
{
cntClosing = (cntClosing + 1) % 2;
if (cntClosing == 0 &&
st.Count != 0)
{
st.Pop();
}
}
}
operationCnt += st.Count * 2 -
cntClosing + 1;
return operationCnt;
}
public static void Main(String[] args)
{
String str = "}}{" ;
int len = str.Length;
Console.Write(minOperations(str,
len));
}
}
|
Javascript
<script>
function minOperations(s, len)
{
var operationCnt = 0;
var st = [];
var cntClosing = 0;
for ( var i = 0; i < len; i++) {
if (s[i] == '{' ) {
if (cntClosing > 0) {
operationCnt++;
st.pop();
}
st.push(s[i]);
cntClosing = 0;
}
else if (st.length==0) {
st.push( '{' );
operationCnt++;
cntClosing = 1;
}
else {
cntClosing = (cntClosing + 1) % 2;
if (cntClosing == 0) {
st.pop();
}
}
}
operationCnt += st.length * 2 - cntClosing;
return operationCnt;
}
var str = "}}{" ;
var len = str.length;
document.write( minOperations(str, len));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...