Regarding redundant Parenthesis

https://online.codingblocks.com/player/14796/content/5292?s=3213
please tell how to approach this problem

Hi Kushagra, the idea here is to use stack. Iterate through the given expression and for each character in the expression, if the character is a ‘(‘ or any of the operators or operands, push it to the top of the stack. But when you encounter a ‘)’, then pop characters from the stack till ‘(‘ is found .
for ex

// INPUT
( ( a + b ) + ( ( c + d ) ) )

INSIDE THE STACK
[] //Empty at first
[ ( ]
[ ( , ( ]

[ ( , ( , a , + , b ]
// Now next ‘)’ will be encountered so we pop from stack until we encounter a ‘(’
[ ( , ( , a , + ]
[ ( , ( , a ]
[ ( , ( ]
[ ( ]
// We popped till we found a ‘(’ and after popping it we stopped and resumed on iterating our input.
[ ( ] //Condition of stack after popping was over
[ ( , + ]
[ ( , + , ( ]

[ ( , + , ( , ( , c , + , d ]
Now we start popping again since we encountered a ‘(’

And we will keep processing our input like this. For the condition of extra parentheses we can say that extra parentheses will present in only that condition where we have a stack as:

[ ( ]

and iterating over our input we encounter a ‘)’. Now you just need to detect that condition and you will have your answer then.

I think by now you must have got an idea on how to solve this problem.
Hope this helps :slight_smile:

1 Like