Minimum Bracket Addition in C++


Suppose we have a string s containing only '(' and ')', we have to find the minimum number of brackets that can be inserted to make the string balanced.

So, if the input is like "(()))(", then the output will be 2 as "(()))(", this can be made balanced like "((()))()".

To solve this, we will follow these steps −

  • := 0, cnt := 0

  • for initialize i := 0, when i < size of s, update (increase i by 1), do −

    • if s[i] is same as '(', then −

      • (increase o by 1)

    • Otherwise

      • if o is non-zero, then −

        • (decrease o by 1)

      • Otherwise

        • (increase cnt by 1)

  • return cnt + o

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(string s) {
      int o = 0;
      int cnt = 0;
      for(int i = 0; i < s.size(); i++){
         if(s[i] == '('){
            o++;
         } else {
            if(o)
               o--;
            else
               cnt++;
         }
      }
      return cnt + o;
   }
};
int main(){
   Solution ob;
   cout << (ob.solve("(()))("));
}

Input

Input:
"(()))("

Output

2

Updated on: 02-Sep-2020

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements