17. Expression Contains Redundant Bracket or Not
β GFG solution to check if an expression contains redundant brackets using stack-based approach for optimal validation. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given a string of balanced expression s, check if it contains a redundant parenthesis or not. A set of parentheses are redundant if the same sub-expression is surrounded by unnecessary or multiple brackets.
The expression may contain +, -, *, and / operators. The given expression is valid and there are no white spaces present.
π Examples
Example 1
Input: s = "((a+b))"
Output: true
Explanation: ((a+b)) can be reduced to (a+b).Example 2
Input: s = "(a+(b)/c)"
Output: true
Explanation: (a+(b)/c) can be reduced to (a+b/c) because b is surrounded by () which is redundant.Example 3
π Constraints
$1 \le |s| \le 10^5$
β
My Approach
The optimal approach uses a Stack-Based technique to efficiently detect redundant parentheses by tracking operators between bracket pairs:
Stack-Based Operator Detection
Initialize Stack:
Use a stack to store opening brackets and operators.
Process each character in the expression sequentially.
Character Processing:
For opening brackets
(and operators (+,-,*,/), push them onto the stack.Skip operands (variables/numbers) as they don't affect redundancy.
Closing Bracket Detection:
When encountering
), pop elements from stack until(is found.Track if any operator exists between the bracket pair using a boolean flag.
Redundancy Check:
If no operator is found between a parenthesis pair, return
true(redundant).If an operator exists, the brackets are necessary, continue checking.
Final Result:
If all bracket pairs contain operators, return
false(no redundancy).
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the length of the string. Each character is pushed and popped from the stack at most once, resulting in linear time processing.
Expected Auxiliary Space Complexity: O(n), as in the worst case (highly nested expression), the stack may store all opening brackets and operators, which is proportional to the input size.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated