The Wayback Machine - https://web.archive.org/web/20240910170733/https://www.geeksforgeeks.org/expression-contains-redundant-bracket-not/
Open In App

Expression contains redundant bracket or not

Last Updated : 28 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
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
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
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
Convert Infix expression to Postfix expression
Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +
13 min read
Check if a String Contains Only Alphabets in Java Using Lambda Expression
Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces. Given a String, we just need to iterate over characters again th
3 min read
Number of closing brackets needed to complete a regular bracket sequence
Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete the bracket sequence, print "IMPOSSIBLE". Let us def
7 min read
Check if a given string can be converted to a Balanced Bracket Sequence
Given a string S of size N consisting of '(', ')', and '$', the task is to check whether the given string can be converted into a balanced bracket sequence by replacing every occurrence of $ with either ) or (. A balanced bracket sequence is a sequence where every opening bracket "(" has a corresponding closing bracket ")". Examples: Input: S = "()
12 min read
Range Queries for Longest Correct Bracket Subsequence
Given a bracket sequence or in other words a string S of length n, consisting of characters '(' and ')'. Find the length of the maximum correct bracket subsequence of sequence for a given query range Note: A correct bracket sequence is the one that has matched bracket pairs or which contains another nested correct bracket sequence. For e.g (), (())
15+ min read
Find the lexicographical next balanced bracket sequence
Given a balanced bracket sequence as a string str containing character '(' or ')', the task is to find the next lexicographical order balanced sequence if possible else print -1.Examples: Input: str = "(())" Output: ()()Input: str = "((()))" Output: (()()) Approach: First find the rightmost opening bracket which we can replace it by a closing brack
6 min read
Number of balanced bracket subsequence of length 2 and 4
Given a bracket sequence of even length. The task is to find how many ways are there to make balanced bracket subsequences from the given sequence of length 2 and 4. The sequence () is a bracket sequence of length 2. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of t
9 min read
Minimum sum possible of any bracket sequence of length N
Given a number N representing the length of a bracket sequence consisting of brackets '(', ')'. The actual sequence is not known beforehand. Given the values of both brackets '(' and ')' if placed at index [Tex]i [/Tex]in the expression. The task is to find the minimum sum possible of any bracket sequence of length N using the above information.Her
8 min read
Number of balanced bracket expressions that can be formed from a string
Given a string str comprising of characters (, ), {, }, [, ] and ?. The task is to find the total number of balanced bracket expressions formed when ? can be replaced with any of the bracket characters. Here are some examples of balanced bracket expressions: {([])}, {()}[{}] etc. And, unbalanced bracket expressions: {[}, {()], {()}[) etc. Examples:
12 min read
Convert an unbalanced bracket sequence to a balanced sequence
Given an unbalanced bracket sequence of '(' and ')', convert it into a balanced sequence by adding the minimum number of '(' at the beginning of the string and ')' at the end of the string. Examples: Input: str = ")))()" Output: "((()))()" Input: str = "())())(())())" Output: "(((())())(())())" Method 1: Approach: Initialize an empty stack.Iterate
13 min read
Minimum Cost required to generate a balanced Bracket Sequence
Given a string str of length N, representing a bracket sequence, and two integers A and B, the task is to find the minimum cost required to obtain a regular bracket sequence from str by performing any number of moves(possibly zero) of the following types: Remove a character from the string for a cost A.Remove a character from the string and append
9 min read
Construct a Binary Tree from String with bracket representation | Set 2
Given a string s consisting of parentheses {'(' and ')'} and integers, the task is to construct a Binary Tree from it and print its Preorder traversal. Examples: Input: S = "1(2)(3)"Output: 1 2 3Explanation: The corresponding binary tree is as follows: 1 / \ 2 3 Input: "4(2(3)(1))(6(5))"Output: 4 2 3 1 6 5Explanation:The corresponding binary tree i
9 min read
Check if a Regular Bracket Sequence can be formed with concatenation of given strings
Given an array arr[] consisting of N strings where each string consists of '(' and ')', the task is to check if a Regular Bracket Sequence can be formed with the concatenation of the given strings or not. If found to be true, then print Yes. Otherwise print No. Examples: Input: arr[] = { ")", "()(" }Output: YesExplanation: The valid string is S[1]
11 min read
Mastering Bracket Problems for Competitive Programming
Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve checking if a given sequence of these symbols is well-
4 min read
Print all ways to break a string in bracket form
Given a string, find all ways to break the given string in bracket form. Enclose each substring within a parenthesis. Examples: Input : abc Output: (a)(b)(c) (a)(bc) (ab)(c) (abc) Input : abcd Output : (a)(b)(c)(d) (a)(b)(cd) (a)(bc)(d) (a)(bcd) (ab)(c)(d) (ab)(cd) (abc)(d) (abcd) We strongly recommend you to minimize your browser and try this your
4 min read
Construct Binary Tree from String with bracket representation
Construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure. Always start to construct the left c
15+ min read
Print Bracket Number
Given an expression exp of length n consisting of some brackets. The task is to print the bracket numbers when the expression is being parsed. Examples : Input : (a+(b*c))+(d/e) Output : 1 2 2 1 3 3 The highlighted brackets in the given expression (a+(b*c))+(d/e) has been assigned the numbers as: 1 2 2 1 3 3. Input : ((())(())) Output : 1 2 3 3 2 4
7 min read
Minimum Swaps for Bracket Balancing
You are given a string of 2N characters consisting of N '[' brackets and N ']' brackets. A string is considered balanced if it can be represented in the form S2[S1] where S1 and S2 are balanced strings. We can make an unbalanced string balanced by swapping adjacent characters. Calculate the minimum number of swaps necessary to make a string balance
15+ min read
Range Queries for Longest Correct Bracket Subsequence Set | 2
Given a bracket sequence or in other words a string S of length n, consisting of characters ‘(‘ and ‘)’. Find the length of the maximum correct bracket subsequence of sequence for a given query range. Note: A correct bracket sequence is the one that has matched bracket pairs or which contains another nested correct bracket sequence. For e.g (), (()
8 min read
How to check string is alphanumeric or not using Regular Expression
Given string str, the task is to check whether the string is alphanumeric or not by using Regular Expression. An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9. Examples: Input: str = "GeeksforGeeks123" Output: true Explanation: This string contains all the alphabets from a-z, A-Z, and the numbe
5 min read
Practice Tags :