also tell differnt methods to solve this problem including bruteforce
Please explain this problem and method to solve it
hello @KetanPandey
Sample Input
2
(((a+(b))+(c+d)))
((a+(b))+(c+d))
Sample Output
Duplicate
Not Duplicates
You just have to check here that if there are unnecessary parenthesis or not.
In the 1st case (((a+(b))+(c+d))) you can observe that the first parenthesis pair is not necessary(this expression could be represented by ((a+(b))+(c+d)) ) hence you have to print Duplicate.
In case 2 there is no unnecessary parenthesis so you print Not Duplicates
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 or equal to 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.
i got this approach.Can you tell approach other than using stack
we can balance paranthesis only using stack so there is no other approach without using stack.
and one problem in you solution,you said if counter is equal to 0 or 1,than a duplicate parenthesis is found,why you included 1,it should be only 0
because if counter is 1,so there must be some element inside the parenthesis which is absolutely fine
yeah it should be 0 …