Expression contains redundant bracket or not
Given a string of balanced expressions, find if it contains a redundant parenthesis or not. A set of parenthesis is redundant if the same sub-expression is surrounded by unnecessary or multiple brackets. Print ‘Yes‘ if redundant, else ‘No‘.
Note: Expression may contain ‘+‘, ‘*‘, ‘–‘ and ‘/‘ operators. Given expression is valid and there are no white spaces present.
Input: str = “((a+b))”
Explanation: ((a+b)) can reduced to (a+b), this Redundant
Input: str = “(a+(b)/c)”
Explanation: (a+(b)/c) can reduced to (a+b/c) because b is surrounded by () which is redundant.
Checking Redundant Bracket using Stack
The idea is to use the stack, For any sub-expression of expression, if we are able to pick any sub-expression of expression surrounded by (), then we are again left with ( ) as part of the string, we have redundant braces.
Follow the steps mentioned below to implement the approach:
- 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 conditions 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 the 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 contains unwanted () around a thus it is redundant.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)