Open In App

Find if an expression has duplicate parenthesis or not

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a balanced expression, find if it contains duplicate parenthesis or not. A set of parenthesis are duplicate if the same subexpression is surrounded by multiple parenthesis. 

Examples: 

Below expressions have duplicate parenthesis - 
((a+b)+((c+d)))
The subexpression "c+d" is surrounded by two
pairs of brackets.

(((a+(b)))+(c+d))
The subexpression "a+(b)" is surrounded by two 
pairs of brackets.

(((a+(b))+c+d))
The whole expression is surrounded by two 
pairs of brackets.

((a+(b))+(c+d))
(b) and ((a+(b)) is surrounded by two
pairs of brackets but, it will not be counted as duplicate.

Below expressions don't have any duplicate parenthesis -
((a+b)+(c+d)) 
No subexpression is surrounded by duplicate
brackets.

It may be assumed that the given expression is valid and there are not any white spaces present. 

The idea is to use stack. Iterate through the given expression and for each character in the expression, if the character is a open parenthesis ‘(‘ or any of the operators or operands, push it to the top of the stack. If the character is close parenthesis ‘)’, then pop characters from the stack till matching open parenthesis ‘(‘ is found and a counter is used, whose value is incremented for every character encountered till the opening parenthesis ‘(‘ is found. If the number of characters encountered between the opening and closing parenthesis pair, which is equal to the value of the counter, is less than 1, then a pair of duplicate parenthesis is found else there is no occurrence of redundant parenthesis pairs. For example, (((a+b))+c) has duplicate brackets around “a+b”. When the second “)” after a+b is encountered, the stack contains “((“. Since the top of stack is a opening bracket, it can be concluded that there are duplicate brackets.

Below is the implementation of above idea : 

C++




// C++ program to find duplicate parenthesis in a
// balanced expression
#include <bits/stdc++.h>
using namespace std;
 
// Function to find duplicate parenthesis in a
// balanced expression
bool findDuplicateparenthesis(string str)
{
    // create a stack of characters
    stack<char> Stack;
 
    // Iterate through the given expression
    for (char ch : str)
    {
        // if current character is close parenthesis ')'
        if (ch == ')')
        {
            // pop character from the stack
            char top = Stack.top();
            Stack.pop();
 
            // stores the number of characters between a
            // closing and opening parenthesis
            // if this count is less than or equal to 1
            // then the brackets are redundant else not
            int elementsInside = 0;
            while (top != '(')
            {
                elementsInside++;
                top = Stack.top();
                Stack.pop();
            }
            if(elementsInside < 1) {
                return 1;
            }
        }
 
        // push open parenthesis '(', operators and
        // operands to stack
        else
            Stack.push(ch);
    }
 
    // No duplicates found
    return false;
}
 
 
// Driver code
int main()
{
    // input balanced expression
    string str = "(((a+(b))+(c+d)))";
 
    if (findDuplicateparenthesis(str))
        cout << "Duplicate Found ";
    else
        cout << "No Duplicates Found ";
 
    return 0;
}


Java




import java.util.Stack;
 
// Java program to find duplicate parenthesis in a
// balanced expression
public class GFG {
 
// Function to find duplicate parenthesis in a
// balanced expression
    static boolean findDuplicateparenthesis(String s) {
        // create a stack of characters
        Stack<Character> Stack = new Stack<>();
 
        // Iterate through the given expression
        char[] str = s.toCharArray();
        for (char ch : str) {
            // if current character is close parenthesis ')'
            if (ch == ')') {
                // pop character from the stack
                char top = Stack.peek();
                Stack.pop();
 
                // stores the number of characters between a
                // closing and opening parenthesis
                // if this count is less than or equal to 1
                // then the brackets are redundant else not
                int elementsInside = 0;
                while (top != '(') {
                    elementsInside++;
                    top = Stack.peek();
                    Stack.pop();
                }
                if (elementsInside < 1) {
                    return true;
                }
            } // push open parenthesis '(', operators and
            // operands to stack
            else {
                Stack.push(ch);
            }
        }
 
        // No duplicates found
        return false;
    }
 
// Driver code
public static void main(String[] args) {
 
        // input balanced expression
        String str = "(((a+(b))+(c+d)))";
 
        if (findDuplicateparenthesis(str)) {
            System.out.println("Duplicate Found ");
        } else {
            System.out.println("No Duplicates Found ");
        }
 
    }
}


Python3




# Python3 program to find duplicate
# parenthesis in a balanced expression
 
# Function to find duplicate parenthesis
# in a balanced expression
def findDuplicateparenthesis(string):
 
    # create a stack of characters
    Stack = []
 
    # Iterate through the given expression
    for ch in string:
     
        # if current character is
        # close parenthesis ')'
        if ch == ')':
         
            # pop character from the stack
            top = Stack.pop()
 
            # stores the number of characters between
            # a closing and opening parenthesis
            # if this count is less than or equal to 1
            # then the brackets are redundant else not
            elementsInside = 0
            while top != '(':
             
                elementsInside += 1
                top = Stack.pop()
             
            if elementsInside < 1:
                return True
 
        # push open parenthesis '(', operators
        # and operands to stack
        else:
            Stack.append(ch)
     
    # No duplicates found
    return False
 
# Driver Code
if __name__ == "__main__":
 
    # input balanced expression
    string = "(((a+(b))+(c+d)))"
 
    if findDuplicateparenthesis(string) == True:
        print("Duplicate Found")
    else:
        print("No Duplicates Found")
 
# This code is contributed by Rituraj Jain


C#




// C# program to find duplicate parenthesis
// in a balanced expression
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to find duplicate parenthesis 
// in a balanced expression
static Boolean findDuplicateparenthesis(String s)
{
    // create a stack of characters
    Stack<char> Stack = new Stack<char>();
 
    // Iterate through the given expression
    char[] str = s.ToCharArray();
    foreach (char ch in str)
    {
        // if current character is
        // close parenthesis ')'
        if (ch == ')')
        {
            // pop character from the stack
            char top = Stack.Peek();
            Stack.Pop();
 
            // stores the number of characters between
            // a closing and opening parenthesis
            // if this count is less than or equal to 1
            // then the brackets are redundant else not
            int elementsInside = 0;
            while (top != '(')
            {
                elementsInside++;
                top = Stack.Peek();
                Stack.Pop();
            }
            if (elementsInside < 1)
            {
                return true;
            }
        
         
        // push open parenthesis '(',
        // operators and operands to stack
        else
        {
            Stack.Push(ch);
        }
    }
 
    // No duplicates found
    return false;
}
 
// Driver code
public static void Main(String[] args)
{
 
    // input balanced expression
    String str = "(((a+(b))+(c+d)))";
 
    if (findDuplicateparenthesis(str))
    {
        Console.WriteLine("Duplicate Found ");
    }
    else
    {
        Console.WriteLine("No Duplicates Found ");
    }
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript program to find duplicate
// parenthesis in a balanced expression
 
// Function to find duplicate parenthesis
// in a balanced expression
function findDuplicateparenthesis(s)
{
     
    // Create a stack of characters
    let Stack = [];
 
    // Iterate through the given expression
    let str = s.split("");
    for(let ch = 0; ch < str.length;ch++)
    {
         
        // If current character is close
        // parenthesis ')'
        if (str[ch] == ')')
        {
             
            // pop character from the stack
            let top = Stack.pop();
             
            // Stores the number of characters between a
            // closing and opening parenthesis
            // if this count is less than or equal to 1
            // then the brackets are redundant else not
            let elementsInside = 0;
            while (top != '(')
            {
                elementsInside++;
                top = Stack.pop();
            }
            if (elementsInside < 1)
            {
                return true;
            }
        }
         
        // push open parenthesis '(', operators
        // and operands to stack
        else
        {
            Stack.push(str[ch]);
        }
    }
 
    // No duplicates found
    return false;
}
 
// Driver code
let str = "(((a+(b))+(c+d)))";
 
// Input balanced expression
if (findDuplicateparenthesis(str))
{
    document.write("Duplicate Found ");
}
else
{
    document.write("No Duplicates Found ");
}
 
// This code is contributed by rag2127
 
</script>


Output: 

Duplicate Found

Time complexity of above solution is O(n). 

Auxiliary space used by the program is O(n).

 



Previous Article
Next Article

Similar Reads

Find a valid parenthesis sequence of length K from a given valid parenthesis sequence
Given a string S of valid parentheses sequence of length N and an even integer K, the task is to find the valid parentheses sequence of length K which is also a subsequence of the given string. Note: There can be more than one valid sequence, print any of them. Examples: Input: S = "()()()", K = 4Output: ()()Explanation:The string "()()" is a subse
7 min read
Identify and mark unmatched parenthesis in an expression
Given an expression, find and mark matched and unmatched parenthesis in it. We need to replace all balanced opening parenthesis with 0, balanced closing parenthesis with 1, and all unbalanced with -1.Examples: Input : ((a) Output : -10a1 Input : (a)) Output : 0a1-1 Input : (((abc))((d))))) Output : 000abc1100d111-1-1 The idea is based on a stack. W
6 min read
InfyTQ 2019 : Find the position from where the parenthesis is not balanced
Given a string str consisting of parenthesis from [ "(" , ")" , "{" , "}" , "[" , "]" ]. If the String is perfectly balanced return 0 else return the index(starting from 1)at which the nesting is found to be wrong.Examples: Input : str = "{[()]}[]" Output : 0Input : str = "[{]()}" Output : 3Input : str = "}[{}]" Output : 1Input : str = "{([]){" Out
9 min read
Check if a Binary Tree (not BST) has duplicate values
Check if a Binary Tree (not BST) has duplicate values To check if a binary tree has duplicate values, you can follow these steps: Create a set to store the values that have been encountered so far.Start a traversal of the binary tree. For each node, check if its value is in the set. If it is, return true to indicate that the tree contains duplicate
10 min read
Check if a binary string has a 0 between 1s or not | Set 2 (Regular Expression Approach)
Given a string of 0 and 1, we need to check that the given string is valid or not. The given string is valid when there is no zero is present in between 1's. For example, 1111, 0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not. Examples: Input : 100 Output : VALID Input : 1110001 Output : NOT VALID There is 0 between 1s Input :
3 min read
Find maximum depth of nested parenthesis in a string
We are given a string having parenthesis like below “( ((X)) (((Y))) )” We need to find the maximum depth of balanced parenthesis, like 4 in the above example. Since ‘Y’ is surrounded by 4 balanced parentheses. If parenthesis is unbalanced then return -1. Examples : Input : S = "( a(b) (c) (d(e(f)g)h) I (j(k)l)m)"; Output : 4 Input : S = "( p((q))
9 min read
Building Expression tree from Prefix Expression
Given a character array a[] represents a prefix expression. The task is to build an Expression Tree for the expression and then print the infix and postfix expression of the built tree. Examples: Input: a[] = "*+ab-cd" Output: The Infix expression is: a + b * c - d The Postfix expression is: a b + c d - *Input: a[] = "+ab" Output: The Infix express
8 min read
Convert Infix expression to Postfix expression
Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +
13 min read
Remove longest prefix of the String which has duplicate substring
Given a string S of length N, the task is to remove the longest prefix of the string which has at least one duplicate substring present in S. Note: The duplicate substring cannot be the prefix itself Examples: Input: S = "GeeksforGeeks"Output: "forGeeks"Explanation: The longest substring which has a duplicate is "Geeks".After deleting this the rema
5 min read
Remove all redundant parenthesis
Given a valid expression Exp containing only binary operators '+', '-', '*', '/', and operands, remove all the redundant parenthesis. A set of parenthesis is said to be redundant if, removing them, does not change the value of the expression. Note: The operators '+' and '-' have the same priority. '*' and '/' also have the same priority. '*' and '/
13 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg