Expression contains redundant bracket or not

 Given a string of balanced expression str, 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. Return 1 ifit contains a redundant parenthesis, else 0.

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


Example 1:


Input:

exp = ((a+b))

Output:

Yes

Explanation:

((a+b)) can reduced to (a+b).

Example 2:


Input:

exp = (a+b+(c+d))

Output:

No

Explanation:

(a+b+(c+d)) doesn't have any redundant or multiple

brackets.

Your task:

You don't have to read input or print anything. Your task is to complete the function checkRedundancy() which takes the string s as input and returns 1 if it contains redundant parentheses else 0.


Constraints:

1<=|str|<=104


Expected Time Complexity: O(N)

Expected Auxiliary Space: O(N)

💡 Approach Using Stack:

  1. Traverse each character of the string.

  2. Push each character to a stack except the closing bracket ).

  3. When a closing bracket ) is found:

    • Pop from the stack until an opening bracket ( is found.

    • Check if any operator (+, -, *, /) was found inside.



public class codefile{
    static boolean check(String s){
           
              Stack<Character> st= new Stack<>();
       
       
        for(char ch:s.toCharArray())
        {
            if(ch ==')')
            {
               boolean operatorFound = false;
                while(!st.isEmpty() && st.peek() !='(')
                {
                    int top=st.pop();
                   
                    if(top =='+'|| top =='-'|| top =='*'|| top =='/')
                    {
                        operatorFound=true;
                    }
                }
                if(!st.isEmpty())
                {
                    st.pop();//remove (
                }
               
                if(!operatorFound)
                {
                    return true;
                }
            }
            else
            {
                st.push(ch);
            }
        }
       
        return false;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence