Open In App

Expression contains redundant bracket or not

Last Updated : 28 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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)



Previous Article
Next Article

Similar Reads

Check if expression contains redundant bracket or not | Set 2
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
5 min read
Find index of closing bracket for a given opening bracket in an expression
Given a string with brackets. If the start index of the open bracket is given, find the index of the closing bracket. Examples: Input : string = [ABC[23]][89] index = 0 Output : 8 The opening bracket at index 0 corresponds to closing bracket at index 8.Recommended PracticeClosing bracket indexTry It! The idea is to use Stack data structure. We trav
7 min read
Check if the bracket sequence can be balanced with at most one change in the position of a bracket
Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(())"Input: str = "()))(()" Output: No Approach: Co
6 min read
Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Set 2
Given a bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(())"Input: str = "()))(()" Output: No Approach: The problem ca
5 min read
Maximum Pairs of Bracket Sequences which can be concatenated to form a Regular Bracket Sequence
Given an array arr[] of N strings such that each string consists of characters '(' and ')', the task is to find the maximum number of pairs of strings such that the concatenation of the two strings is a Regular Bracket Sequence. A Regular Bracket Sequence is a string consisting of brackets '(' and ')' such that every prefix from the beginning of th
9 min read
Print the balanced bracket expression using given brackets
Given four integers a, b, c and d which signifies the number of four types of brackets. "((""()"")(""))" The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. In case of multiple answers, print any one. Examples: Input: a = 3, b = 1, c = 4, d = 3 Output: (((
6 min read
Minimum number of bracket reversals needed to make an expression balanced | Set - 2
Given an expression with only '}' and '{'. The expression may not be balanced. The task is to find minimum number of bracket reversals to make the expression balanced.Examples: Input : exp = "}{"Output : 2We need to change '}' to '{' and '{' to'}' so that the expression becomes balanced, the balanced expression is '{}'Input : exp = "}{{}}{{{"Output
11 min read
Minimum number of bracket reversals needed to make an expression balanced
Given an expression with only '}' and '{'. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.Examples: Input: exp = "}{"Output: 2We need to change '}' to '{' and '{' to'}' so that the expression becomes balanced, the balanced expression is '{}'Input: exp = "{{{"Output: Can't be made balance
15+ min read
Remove all redundant parenthesis
Given a valid expression Exp containing only binary operators '+', '-', '*', '/', and operands, remove all the redundant parenthesis. A set of parenthesis is said to be redundant if, removing them, does not change the value of the expression. Note: The operators '+' and '-' have the same priority. '*' and '/' also have the same priority. '*' and '/
13 min read
Count distinct regular bracket sequences which are not N periodic
Given an integer N, the task is to find the number of distinct bracket sequences that can be formed using 2 * N brackets such that the sequence is not N-periodic. A bracket sequence str of length 2 * N is said to be N-periodic if the sequence can be split into two equal substrings having same regular bracket sequence.A regular bracket sequence is a
8 min read
Practice Tags :
three90RightbarBannerImg