Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Expression contains redundant bracket or not

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.

Examples: 

Input: str = “((a+b))”
Output: YES
Explanation: ((a+b)) can reduced to (a+b), this Redundant

Input: str = “(a+(b)/c)”
Output: YES
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:

C++




/* C++ Program to check whether valid
 expression is redundant or not*/
#include <bits/stdc++.h>
using namespace std;
 
// Function to check redundant brackets in a
// balanced expression
bool checkRedundancy(string& str)
{
    // create a stack of characters
    stack<char> st;
 
    // Iterate through the given expression
    for (auto& ch : str) {
 
        // if current character is close parenthesis ')'
        if (ch == ')') {
            char top = st.top();
            st.pop();
 
            // If immediate pop have open parenthesis '('
            // duplicate brackets found
            bool flag = true;
 
            while (!st.empty() and top != '(') {
 
                // Check for operators in expression
                if (top == '+' || top == '-' ||
                    top == '*' || top == '/')
                    flag = false;
 
                // Fetch top element of stack
                top = st.top();
                st.pop();
            }
 
            // If operators not found
            if (flag == true)
                return true;
        }
 
        else
            st.push(ch); // push open parenthesis '(',
                  // operators and operands to stack
    }
    return false;
}
 
// Function to check redundant brackets
void findRedundant(string& str)
{
    bool ans = checkRedundancy(str);
    if (ans == true)
        cout << "Yes\n";
    else
        cout << "No\n";
}
 
// Driver code
int main()
{
    string str = "((a+b))";
    findRedundant(str);
    return 0;
}


Java




/* Java Program to check whether valid
expression is redundant or not*/
import java.util.Stack;
public class GFG {
// Function to check redundant brackets in a
// balanced expression
 
    static boolean checkRedundancy(String s) {
        // create a stack of characters
        Stack<Character> st = new Stack<>();
        char[] str = s.toCharArray();
        // Iterate through the given expression
        for (char ch : str) {
 
            // if current character is close parenthesis ')'
            if (ch == ')') {
                char top = st.peek();
                st.pop();
 
                // If immediate pop have open parenthesis '('
                // duplicate brackets found
                boolean flag = true;
 
                while (top != '(') {
 
                    // Check for operators in expression
                    if (top == '+' || top == '-'
                            || top == '*' || top == '/') {
                        flag = false;
                    }
 
                    // Fetch top element of stack
                    top = st.peek();
                    st.pop();
                }
 
                // If operators not found
                if (flag == true) {
                    return true;
                }
            } else {
                st.push(ch); // push open parenthesis '(',
            }                // operators and operands to stack
        }
        return false;
    }
 
// Function to check redundant brackets
    static void findRedundant(String str) {
        boolean ans = checkRedundancy(str);
        if (ans == true) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
 
// Driver code
    public static void main(String[] args) {
        String str = "((a+b))";
        findRedundant(str);
 
    }
}


Python3




# Python3 Program to check whether valid
# expression is redundant or not
 
# Function to check redundant brackets
# in a balanced expression
def checkRedundancy(Str):
     
    # create a stack of characters
    st = []
 
    # Iterate through the given expression
    for ch in Str:
 
        # if current character is close
        # parenthesis ')'
        if (ch == ')'):
            top = st[-1]
            st.pop()
 
            # If immediate pop have open parenthesis
            # '(' duplicate brackets found
            flag = True
 
            while (top != '('):
 
                # Check for operators in expression
                if (top == '+' or top == '-' or
                    top == '*' or top == '/'):
                    flag = False
 
                # Fetch top element of stack
                top = st[-1]
                st.pop()
 
            # If operators not found
            if (flag == True):
                return True
 
        else:
            st.append(ch) # append open parenthesis '(',
                          # operators and operands to stack
    return False
 
# Function to check redundant brackets
def findRedundant(Str):
    ans = checkRedundancy(Str)
    if (ans == True):
        print("Yes")
    else:
        print("No")
 
# Driver code
if __name__ == '__main__':
    Str = "((a+b))"
    findRedundant(Str)
 
 
# This code is contributed by PranchalK


C#




/* C# Program to check whether valid
expression is redundant or not*/
using System;
using System.Collections.Generic;
 
class GFG
{
    // Function to check redundant brackets in a
    // balanced expression
    static bool checkRedundancy(String s)
    {
        // create a stack of characters
        Stack<char> st = new Stack<char>();
        char[] str = s.ToCharArray();
         
        // Iterate through the given expression
        foreach (char ch in str)
        {
 
            // if current character is close parenthesis ')'
            if (ch == ')')
            {
                char top = st.Peek();
                st.Pop();
 
                // If immediate pop have open parenthesis '('
                // duplicate brackets found
                bool flag = true;
 
                while (top != '(')
                {
 
                    // Check for operators in expression
                    if (top == '+' || top == '-'
                            || top == '*' || top == '/')
                    {
                        flag = false;
                    }
 
                    // Fetch top element of stack
                    top = st.Peek();
                    st.Pop();
                }
 
                // If operators not found
                if (flag == true)
                {
                    return true;
                }
            }
            else
            {
                st.Push(ch); // push open parenthesis '(',
            }         // operators and operands to stack
        }
        return false;
    }
 
    // Function to check redundant brackets
    static void findRedundant(String str)
    {
        bool ans = checkRedundancy(str);
        if (ans == true)
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String str = "((a+b))";
        findRedundant(str);
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript




<script>
 
/* JavaScript Program to check whether valid
 expression is redundant or not*/
 
 
// Function to check redundant brackets in a
// balanced expression
function checkRedundancy(str)
{
    // create a stack of characters
    var st = [];
    var ans = false;
    // Iterate through the given expression
    str.split('').forEach(ch => {
         
 
        // if current character is close parenthesis ')'
        if (ch == ')') {
            var top = st[st.length-1];
            st.pop();
 
            // If immediate pop have open parenthesis '('
            // duplicate brackets found
            var flag = true;
 
            while (st.length!=0 && top != '(') {
 
                // Check for operators in expression
                if (top == '+' || top == '-' ||
                    top == '*' || top == '/')
                    flag = false;
 
                // Fetch top element of stack
                top = st[st.length-1];
                st.pop();
            }
 
            // If operators not found
            if (flag == true)
                ans = true;
        }
 
        else
            st.push(ch); // push open parenthesis '(',
                  // operators and operands to stack
    });
    return ans;
}
 
// Function to check redundant brackets
function findRedundant(str)
{
    var ans = checkRedundancy(str);
    if (ans == true)
        document.write( "Yes<br>");
    else
        document.write( "No<br>");
}
 
// Driver code
 
var str = "((a+b))";
findRedundant(str);
 
 
 
</script>


Output

Yes

Time Complexity: O(N)
Auxiliary Space: O(N)

Using a count variable: The intuition behind this approach is that if an opening bracket is followed immediately by a closing bracket, then we have a redundant bracket. Similarly, if an opening bracket is followed by a non-operator character and then a closing bracket, then we have a redundant bracket. However, if an opening bracket is followed by an operator and then a closing bracket, then the brackets are not redundant since the operator may have a different precedence level than the operators outside the brackets.

By keeping track of the opening brackets using a counter variable, we can easily determine if a closing bracket is redundant or not. If the counter count is less than or equal to 1 when we encounter a closing bracket, then we know that there is no non-operator character between the opening and closing brackets, so the brackets are redundant. Overall, the “Using a Count” approach is a simple and efficient way to find redundant brackets in a string of balanced expressions.

Below is the implementation for the above approach,

C++




//C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the given character is an operator
// or not
bool isOperator(char c)
{
    if (c == '+' || c == '-' || c == '*' || c == '/') {
        return true;
    }
    return false;
}
 
// Function to check if the given string contains redundant
// brackets or not
bool hasRedundantBrackets(string str)
{
    int n = str.length();
    int count = 0;
 
    for (int i = 0; i < n; i++) {
        if (str[i] == '(') {
            count++;
        }
        else if (str[i] == ')') {
            if (count <= 1) {
                return true;
            }
            else {
                count--;
                while (i < n - 1
                       && isOperator(str[i + 1])) {
                    i += 2;
                }
            }
        }
        else if (isOperator(str[i])) {
            continue;
        }
    }
 
    return false;
}
 
// Driver code
int main()
{
    string str = "((a+b))";
 
    if (hasRedundantBrackets(str)) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }
 
    return 0;
}
//This code is contributed by Veerendra_Singh_Rajpoot


Java




import java.util.*;
 
public class Gfg {
     
    // Function to check if the given character is an operator or not
    static boolean isOperator(char c) {
        if (c == '+' || c == '-' || c == '*' || c == '/') {
            return true;
        }
        return false;
    }
 
    // Function to check if the given string contains redundant brackets or not
    static boolean hasRedundantBrackets(String str) {
        int n = str.length();
        int count = 0;
 
        for (int i = 0; i < n; i++) {
            if (str.charAt(i) == '(') {
                count++;
            }
            else if (str.charAt(i) == ')') {
                if (count <= 1) {
                    return true;
                }
                else {
                    count--;
                    while (i < n - 1 && isOperator(str.charAt(i + 1))) {
                        i += 2;
                    }
                }
            }
            else if (isOperator(str.charAt(i))) {
                continue;
            }
        }
 
        return false;
    }
 
    // Driver code
    public static void main(String[] args) {
        String str = "((a+b))";
 
        if (hasRedundantBrackets(str)) {
            System.out.println("YES");
        }
        else {
            System.out.println("NO");
        }
    }
}


Python3




# Function to check if the given character is an operator or not
def isOperator(c):
    if c == '+' or c == '-' or c == '*' or c == '/':
        return True
    return False
 
# Function to check if the given string contains redundant brackets or not
def hasRedundantBrackets(str):
    n = len(str)
    count = 0
 
    for i in range(n):
        if str[i] == '(':
            count += 1
        elif str[i] == ')':
            if count <= 1:
                return True
            else:
                count -= 1
                while i < n - 1 and isOperator(str[i + 1]):
                    i += 2
        elif isOperator(str[i]):
            continue
 
    return False
 
# Driver code
str = "((a+b))"
if hasRedundantBrackets(str):
    print("YES")
else:
    print("NO")
     
# This code is contributed by sdeadityasharma


C#




using System;
 
public class RedundantBrackets
{
  // Function to check if the given character is an operator
  // or not
  static bool IsOperator(char c)
  {
    if (c == '+' || c == '-' || c == '*' || c == '/')
    {
      return true;
    }
    return false;
  }
 
  // Function to check if the given string contains redundant
  // brackets or not
  static bool HasRedundantBrackets(string str)
  {
    int n = str.Length;
    int count = 0;
 
    for (int i = 0; i < n; i++)
    {
      if (str[i] == '(')
      {
        count++;
      }
      else if (str[i] == ')')
      {
        if (count <= 1)
        {
          return true;
        }
        else
        {
          count--;
          while (i < n - 1 && IsOperator(str[i + 1]))
          {
            i += 2;
          }
        }
      }
      else if (IsOperator(str[i]))
      {
        continue;
      }
    }
 
    return false;
  }
 
  // Driver code
  public static void Main()
  {
    string str = "((a+b))";
 
    if (HasRedundantBrackets(str))
    {
      Console.WriteLine("YES");
    }
    else
    {
      Console.WriteLine("NO");
    }
  }
}


Javascript




// Function to check if the given character is an operator or not
function isOperator(c) {
if (c == '+' || c == '-' || c == '*' || c == '/') {
return true;
}
return false;
}
 
// Function to check if the given string contains redundant brackets or not
function hasRedundantBrackets(str) {
let n = str.length;
let count = 0; for (let i = 0; i < n; i++) {
    if (str[i] == '(') {
        count += 1;
    } else if (str[i] == ')') {
        if (count <= 1) {
            return true;
        } else {
            count -= 1;
            while (i < n - 1 && isOperator(str[i + 1])) {
                i += 2;
            }
        }
    } else if (isOperator(str[i])) {
        continue;
    }
}
 
return false;
}
 
// Driver code
let str = "((a+b))";
if (hasRedundantBrackets(str)) {
console.log("YES");
} else {
console.log("NO");
}


Output

YES

Explanation for the above code:

In the hasRedundantBrackets function, we first initialize a counter count to keep track of the opening brackets. We then traverse the input string str from left to right. If we encounter an opening bracket, we increment the counter. If we encounter a closing bracket, we check if the counter is less than or equal to 1. If it is, then we have a redundant bracket. Otherwise, we decrement the counter and skip to the next non-operator character. If we encounter an operator, we simply continue to the next character. Finally, if we reach the end of the string and the counter is greater than 1, we return false since the expression does not have redundant brackets. Otherwise, we return true.

In the main function, we first read the input string from the user and then call the hasRedundantBrackets function to check if the string contains redundant brackets or not. If it does, we print “YES”. Otherwise, we print “NO”.

Time Complexity: O(n), The algorithm traverses the input string from left to right exactly once. Therefore, the time complexity of this algorithm is O(n), where n is the length of the input string.
Auxiliary Space: O(1), The algorithm uses a constant amount of extra space to store the counter count and the index variable i. Therefore, the space complexity of this algorithm is O(1), which is a constant amount of space.


My Personal Notes arrow_drop_up
Last Updated : 22 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials