Skip to content
Related Articles

Related Articles

Improve Article

Expression contains redundant bracket or not

  • Difficulty Level : Medium
  • Last Updated : 15 Sep, 2021

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 ‘Yes’ if redundant, else ‘No’.
Note: Expression may contain ‘+‘, ‘*‘, ‘‘ and ‘/‘ operators. Given expression is valid and there are no white spaces present.
Example: 
 

Input: 
((a+b))
(a+(b)/c)
(a+b*(c-d))
Output: 
Yes
Yes
No

Explanation:
1. ((a+b)) can reduced to (a+b), this Redundant
2. (a+(b)/c) can reduced to (a+b/c) because b is
surrounded by () which is redundant.
3. (a+b*(c-d)) doesn't have any redundant or multiple
brackets.

 

The idea is to use stack, which is discussed in this article. 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- 
 

  1. 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. 
     
  2. 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. 
     

 

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);
 
    str = "(a+(b)/c)";
    findRedundant(str);
 
    str = "(a+b*(c-d))";
    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);
 
        str = "(a+(b)/c)";
        findRedundant(str);
 
        str = "(a+b*(c-d))";
        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)
 
    Str = "(a+(b)/c)"
    findRedundant(Str)
 
    Str = "(a+b*(c-d))"
    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);
 
        str = "(a+(b)/c)";
        findRedundant(str);
 
        str = "(a+b*(c-d))";
        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);
 
str = "(a+(b)/c)";
findRedundant(str);
 
str = "(a+b*(c-d))";
findRedundant(str);
 
 
</script>
Output



Yes
Yes
No

Time complexity: O(n) 
Auxiliary space: O(n)

Another Approach:

Since, it is given that the expression is always valid, we can infer that any pair of valid braces must contain at least 1 operator and 1 operand in order to be valid parenthesis. Thus, it will be enough to check that if a pair of braces contains at least 2 characters or not in order to check redundancy (as all are binary operators). The code for same is given below:

C++




#include<bits/stdc++.h>
using namespace std;
 
bool checkRedundancy(string A) {
    stack<char> st;
    for(char ch : A)
    {
        if(ch == ')')
        {
            int cnt = 0;
            while(!st.empty() and st.top() != '(')
            {
                cnt++;
                st.pop();
            }
            st.pop();
            if(cnt < 2) return 1;
        }
        else st.push(ch);
    }
 
    return 0;
}
 
int main()
{
      string str = "((a+b))";
    cout<<checkRedundancy(str)<<"\n";
  
    str = "(a+(b)/c)";
    cout<<checkRedundancy(str)<<"\n";
  
    str = "(a+b*(c-d))";
    cout<<checkRedundancy(str)<<"\n";
   
      return 0;
}

Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
class GFG {
    public static boolean checkRedundancy(String A)
    {
        Stack<Character> st = new Stack<>();
        for (int i = 0; i < A.length(); i++) {
            char ch = A.charAt(i);
            if (ch == ')') {
                int cnt = 0;
                while (st.empty() == false
                       && st.peek() != '(') {
                    cnt++;
                    st.pop();
                }
                st.pop();
                if (cnt < 2)
                    return true;
            }
            else
                st.push(ch);
        }
        return false;
    }
 
    public static void main(String[] args)
    {
        String str = "((a+b))";
        System.out.println(checkRedundancy(str));
 
        str = "(a+(b)/c)";
        System.out.println(checkRedundancy(str));
 
        str = "(a+b*(c-d))";
        System.out.println(checkRedundancy(str));
    }
}

Python3




def checkRedundancy(A):
    stack = []
 
    s = ""
    just_added = False
    for c in A:
        if c == ')':
            n = 0
            while stack.pop() != '(':
                n += 1
            if n == 0 or n == 1:
                return 1
        else:
            stack.append(c)
 
    return 0
 
 
Str = "((a+b))"
print(checkRedundancy(Str))
 
Str = "(a+(b)/c)"
print(checkRedundancy(Str))
 
Str = "(a+b*(c-d))"
print(checkRedundancy(Str))
Output
1
1
0

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :