- RedundantParenthesis
Given a string of balanced expression, find if it contains a redundant parenthesis or not. A set of parenthesis are redundant if the same sub-expression is surrounded by unnecessary or multiple brackets. Print True if redundant, else False. Note: Expression may contain β+β, β*β, βββ and β/β operators. Given expression is valid and there are no white spaces present. For example:
- ((a+b)) can reduced to (a+b), this is Redundant
- (a+b*(c-d)) doesn't have any redundant or multiple brackets
Stack : Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Redundant : The expression should not have extra brackets.
-
We iterate through the given expression and for each character in the expression, if the character is an open parenthesis β(β or any operators, we push it to the stack.
-
If the character is close parenthesis β)β, then pop characters from the stack till matching open parenthesis β(β is found. For any sub-expression of expression, if we are able to pick any sub-expression of expression surrounded by (), then we again left with () as part of string, we have redundant braces. We iterate through the given expression and for each character in the expression, if the character is an open parenthesis β(β or any of the operators or operands, we push it to the stack. If the character is close parenthesis β)β, then pop characters from the stack till matching open parenthesis β(β is found. Now for redundancy two condition will arise while popping-
-
If immediate pop hits an open parenthesis β(β, then we have found a duplicate parenthesis. For example, (((a+b))+c) has duplicate brackets around a+b. When we reach the second β)β after a+b, we have β((β in the stack. Since the top of stack is an opening bracket, we conclude that there are duplicate brackets.
-
If immediate pop doesnβt hit any operand(β*β, β+β, β/β, β-β) then it indicates the presence of unwanted brackets surrounded by expression. For instance, (a)+b contain unwanted () around a thus it is redundant.
- Only one traversal of the loop is needed.
- There is extra space required.
- Problem is solved in O(N) time complexity.
- Stack made it easier to understand.
- There is extra space required.