Open In App

Expression contains redundant bracket or not

Last Updated : 08 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given a string of balanced expressions, find if it contains a redundant parenthesis or not. Print 'Yes' if redundant, else 'No'.

What are Redundant Parentheses?

A pair of parentheses is redundant if removing them does not change the expression. This happens in two cases:

Extra Parentheses Around an Expression: ((a+b)) → The outermost brackets are unnecessary.
Unnecessary Parentheses Around a Single Element: (a)+b → The parentheses around a are not needed.

Note: Expression may contain '+', '*', '-' and '/' operators. Given expression is valid and there are no white spaces present.

Examples: 

Input: s = "((a+b))"
Output: True
Explanation: ((a+b)) can reduced to (a+b), this Redundant

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

Approach: 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:

  1. Iterate through each character in the given expression.
    • If the character is an open parenthesis (, an operand (a-z), or an operator (+, -, *, /), push it onto the stack.
    • If the character is a closing parenthesis ), we need to check if the parentheses are redundant.
  2. When a closing parenthesis ) is found, pop elements from the stack until an opening parenthesis ( is encountered.
    • While popping, check if there is at least one operator (+, -, *, /).
    • If no operator is found before reaching (, it means the parentheses are redundant.
    • If the top of the stack is an opening ( immediately when popping starts, it also means redundancy.
  3. If redundancy is found, return "True". Otherwise, after checking the entire expression, return "False".
C++
/* C++ Program to check whether valid 
 expression is redundant or not*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

// Function to check redundant brackets in a
// balanced expression
bool checkRedundancy(string& s)
{
    // create a stack of characters
    stack<char> st;

    // Iterate through the given expression
    for (auto& ch : s) {

        // 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); 
             
    }
    return false;
}

// Function to check redundant brackets
void findRedundant(string& s)
{
    bool res = checkRedundancy(s);
    if (res == true)
        cout << "True\n";
    else
        cout << "False\n";
}

int main()
{
    string s = "((a+b))";
    findRedundant(s);
    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 has 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) {
                    return true;
                }
            } else {
                st.push(ch); 
            }              
        }
        return false;
    }

    // Function to check redundant brackets 
    static void findRedundant(String s) {
        boolean res = checkRedundancy(s);
        if (res) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }

    public static void main(String[] args) {
        String s = "((a+b))";
        findRedundant(s);
    }
}
Python
# Python3 Program to check whether valid 
# expression is redundant or not

# Function to check redundant brackets 
# in a balanced expression 
def checkRedundancy(s):
    
    # create a stack of characters 
    st = [] 

    # Iterate through the given expression 
    for ch in s: 

        # if current character is close 
        # parenthesis ')' 
        if ch == ')': 
            top = st[-1] 
            st.pop() 

            # If immediate pop has open parenthesis 
            # '(' duplicate brackets found 
            flag = True

            while top != '(': 

                # Check for operators in expression 
                if top in {'+', '-', '*', '/'}: 
                    flag = False

                # Fetch top element of stack 
                top = st[-1] 
                st.pop()

            # If operators not found 
            if flag:
                return True

        else:
            st.append(ch) 
    return False

# Function to check redundant brackets 
def findRedundant(s):
    res = checkRedundancy(s) 
    if res: 
        print("True") 
    else:
        print("False")

if __name__ == '__main__':
    s = "((a+b))"
    findRedundant(s)
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 has 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); 
            }        
        }
        return false;
    }

    // Function to check redundant brackets 
    static void findRedundant(String s)
    {
        bool res = checkRedundancy(s);
        if (res == true) 
        {
            Console.WriteLine("True");
        } 
        else
        {
            Console.WriteLine("False");
        }
    }

    public static void Main(String[] args) 
    {
        String s = "((a+b))";
        findRedundant(s);
    }
}
JavaScript
/* JavaScript Program to check whether valid 
 expression is redundant or not*/


// Function to check redundant brackets in a
// balanced expression
function checkRedundancy(s)
{
    // create a stack of characters
    var st = [];
    var res = false;
    // Iterate through the given expression
    s.split('').forEach(ch => {
        

        // if current character is close parenthesis ')'
        if (ch == ')') {
            var top = st[st.length-1];
            st.pop();

            // If immediate pop has 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)
                res = true;
        }

        else
            st.push(ch); 
    });
    return res;
}

// Function to check redundant brackets
function findRedundant(s)
{
    var res = checkRedundancy(s);
    if (res == true)
        console.log( "True");
    else
        console.log( "False");
}

// Driver code

var s = "((a+b))";
findRedundant(s);

Output
True

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


Article Tags :
Practice Tags :

Similar Reads