Minimum number of Parentheses to be added to make it valid in C++


Problem statement

Given a string of parentheses. It can container opening parentheses ’(‘ or closing parentheses ‘)’. We have to find minimum number of parentheses to make the resulting parentheses string is valid.

Example

If str = “((()” then we required 2 closing parentheses i.e ‘))’ at end of string

Algorithm

  • Count opening parentheses
  • Count closing parentheses
  • Required parentheses = abs(no. of opening parentheses – no. of closing parentheses)

Example

#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int requiredParentheses(string str) {
   int openingParentheses = 0, closingParentheses = 0;
   for (int i = 0; i < str.length(); ++i) {
      if (str[i] == '(') {
         ++openingParentheses;
      } else if (str[i] == ')') {
         ++closingParentheses;
      }
   }
   return abs(openingParentheses - closingParentheses);
}
int main() {
   string str = "((()";
   cout << "Required parentheses = " << requiredParentheses(str) << endl;
   return 0;
}

When you compile and execute above program. It generates following output −

Required parentheses = 2

Updated on: 22-Nov-2019

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements