VOOZH about

URL: https://www.geeksforgeeks.org/dsa/expression-contains-redundant-bracket-not/

⇱ Check Redundant Brackets - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check Redundant Brackets

Last Updated : 3 Sep, 2025

Given a balanced expression string s, check if it contains redundant parentheses. Return true if redundant, else false.
Redundant Parentheses: Parentheses are redundant if removing them does not change the expression.
Note: Expression is valid, contains operators +, -, *, /, and no spaces.

Examples: 

Input: s = "((a+b))"
Output: true
Explanation: ((a+b)) can be simplified to (a+b), which means the outer parentheses are redundant.

Input: s = "(a+(b)/c)"
Output: true
Explanation: (a+(b)/c) can reduced to (a+b/c) because b is surrounded by () which is redundant.

Input: s = "((a+b)*c)"
Output: false
Explanation: Removing any parentheses would change the order of evaluation, so none of them are redundant.

[Approach] Using Stack - O(n) Time and O(n) Space

Redundant parentheses occur in two cases:

  1. Extra around an expression → ((a+b)) - The outermost brackets are unnecessary.
  2. Around a single element → (a)+b - The parentheses around 'a' are not needed.

The idea is to use a stack so that whenever we encounter a closing parenthesis ')', we can check the element before it. For every such pair, if no operator (+, -, *, /) exists within, then the parentheses are redundant.

Steps to Implement the Approach:

  1. Traverse each character of the expression.
  2. If the character is an opening parenthesis '(', an operand (a–z), or an operator (+, -, *, /), push it onto the stack.
  3. If the character is a closing parenthesis ')':
    => Pop elements from the stack until an opening parenthesis '(' is found.
    => While popping, check if at least one operator (+, -, *, /) exists.
    => If no operator is found (i.e., the parentheses enclose only a single operand or nothing), the parentheses are redundant.
    => If the very first element popped is '(', this also indicates redundancy.
  4. If redundancy is detected, return true.
  5. If the entire expression is scanned without finding redundancy, return false.

Output
true
Comment