Find if an expression has duplicate parenthesis or not in C++

Consider we have an expression exp, and we have to check whether the exp has a duplicate set of parentheses around it or not. An expression will have duplicate parentheses if one sub-expression will be surrounded by more than one parentheses set. For example, if the expression is like −


Here the sub-expression (7 – 3) is surrounded by two parentheses pair, so these are duplicate parentheses.

To solve this problem, we will use stacks. We will iterate through each character in the exp, and if the character is opening parentheses ‘(’, or any of the operator or operand, then push it into the stack. When the character is closing parentheses, then repeatedly pop characters from the stack until the matching opening parentheses has found, and a counter is used, whose value will be incremented for every character encountered between opening and closing parentheses pair. Which is equal to the value of the counter, is less than 1, then pair of duplicate parentheses is found, otherwise not found.


 Live Demo

using namespace std;
bool hasDuplicateParentheses(string str) {
   stack<char> stk;
   for (int i = 0; i<str.length(); i++) {
      char ch = str[i];
      if (ch == ')') {
         char top =;
         int count = 0;
         while (top != '(') {
            top =;
         if(count < 1) {
            return true;
   return false;
int main() {
   string str = "(5+((7-3)))";
   if (hasDuplicateParentheses(str))
      cout << "Duplicate parentheses has Found";
      cout << "No Duplicates parentheses has Found ";


Duplicate parentheses has Found