Parenthesis Checker | Practice | GeeksforGeeks

Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the function should return 'true' for exp = “[()]{}{[()()]()}” and 'false' for exp = “[(])”.
Example 1:
Input:
{([])}
Output: 
true
Explanation: 
{ ( [ ] ) }. Same colored brackets can form 
balaced pairs, with 0 number of 
unbalanced bracket.

Example 2:
Input: 
()
Output: 
true
Explanation: 
(). Same bracket can form balanced pairs, 
and here only 1 type of bracket is 
present and in balanced way.

Example 3:
Input: 
([]
Output: 
false
Explanation: 
([]. Here square bracket is balanced but 
the small bracket is not balanced and 
Hence , the output will be unbalanced.
Your Task:
This is a function problem. You only need to complete the function ispar() that takes a string as a parameter and returns a boolean value true if brackets are balanced else returns false. The printing is done automatically by the driver code.

Expected Time Complexity: O(|x|)
Expected Auixilliary Space: O(|x|)

Constraints:
1 ≤ |x| ≤ 32000
Note: The drive code prints "balanced" if function return true, otherwise it prints "not balanced".
0
21ceuos0839 hours ago
hi
0
21ceuos083
This comment has been flagged for violating our community guidelines.
0
21ceuos083
This comment has been flagged for violating our community guidelines.
0
bhagyeshreddy29112 days ago
class Solution
{
    public:
    //Function to check if brackets are balanced or not.
    bool ispar(string x)
    {
        // Your code here
        stack<char> s;
        
        for(int i = 0; i < x.length(); i++) 
        {
            if(x[i] == '(' || 
               x[i] == '{' ||
               x[i] == '[') 
               {
                s.push(x[i]);
            }
            else {
                if(s.empty() || 
                   (s.top() == '(' && x[i] != ')') ||
                   (s.top() == '{' && x[i] != '}') ||
                   (s.top() == '[' && x[i] != ']')) {
                    return false;
                }
                s.pop();
            }
        }
        return (s.empty());
    }

};

0
aniket6518gadhe2 days ago
JAVA SOLUTION
Total Time Taken:
0.4/1.2
static boolean ispar(String x)
    {
        if(x.length()==1)
            return false;
        Stack<Character> temp = new Stack();
        int i=0;
        temp.push('1');
        while(i<x.length()){
            char ch=x.charAt(i);
            if(ch=='{' || ch=='(' || ch=='[')
                temp.push(ch);
            if(ch=='}'){
                if(temp.peek()=='{')
                    temp.pop();
                else
                    return false;
            }
            if(ch==')'){
                if(temp.peek()=='(')
                    temp.pop();
                else
                    return false;
            }
            if(ch==']'){
                if(temp.peek()=='[')
                    temp.pop();
                else
                    return false;
            }
            i++;
        }
        if(temp.peek()=='1')
            return true;
        return false;
    }
+1
jainmuskan5654 days ago
    //Function to check if brackets are balanced or not.
    static bool check(char b, char a){
        if((a=='(' && b==')') ||(a=='{' && b=='}') ||(a=='[' && b==']') ){
            return true;
        }
        return false;
    }
    bool ispar(string x)
    {
        stack<char> s;
        for(int i=0;i<x.size();i++){
            if(x[i]== '['||x[i]== '{'||x[i]== '(' ){
                s.push(x[i]);
            }
            else{
                if(s.empty()) return false;
                else if(check(x[i],s.top())==false){
                    return false;
                }
                else{
                    s.pop();
                }
            }
        }
        return (s.empty()==true);
    }
+1
shaiksalman9848905 days ago
def ispar(self,x):       # code here       opened={'[':0,'(':1,'{':2}       closed={']':0,')':1,'}':2}              stack=[]       for i in range(len(x)):           if(len(stack)==0 and x[i] in closed):               return 0           if(x[i] in opened):               stack.append(x[i])           if(x[i] in closed):               if(opened[stack[-1]]==closed[x[i]]):                   stack.pop()               else:                   return 0       if(len(stack)>0):           return 0       return 1
0
areeshaanjum7485 days ago
class Solution
{
    //Function to check if brackets are balanced or not.
    static boolean ispar(String x)
    {
        // add your code here
        Stack<Character> st = new Stack<>();
        int n = x.length();
        for(int i = 0; i < n; i++){
            Character ch = x.charAt(i);
            if(ch == '(' || ch == '[' || ch == '{')
                st.push(ch);
            else{
                if(st.empty())
                   return false;
                if((ch == ')' && st.peek() == '(') || (ch == ']' && st.peek() == '[') || (ch == '}' && st.peek() == '{'))
                   st.pop();
                else
                   return false;
                
            }
        }
        
        return st.empty();
        
    }
}
0
vishal8579945 days ago
class Solution{   //Function to check if brackets are balanced or not.   static boolean ispar(String x)   {       //  EASY Java Solutions       Stack<Character>st=new Stack<>();       for(int i=0;i<x.length();i++){           char ch=x.charAt(i);           if(ch=='{' || ch=='[' || ch=='('){               st.push(ch);           }else{               if(st.isEmpty()==true){                   return false;               }else if(cheking(ch,st.lastElement())==false){                   return false;               }else{                   st.pop();               }           }       }       return (st.isEmpty()==true);   }   static boolean cheking(char a,char b){       return ((b=='(' && a==')')||               (b=='[' && a==']')||               (b=='{' && a=='}'));   }} 
+1
muneeralam3205 days ago
PYTHON SOLUTION
def ispar(self,expr):
        stack = []
 
        for char in expr:
            if char in ["(", "{", "["]:
     
                stack.append(char)
            else:
                if not stack:
                    return False
                current_char = stack.pop()
                if current_char == '(':
                    if char != ")":
                        return False
                if current_char == '{':
                    if char != "}":
                        return False
                if current_char == '[':
                    if char != "]":
                        return False
        if stack:
            return False
        return True
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.