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
kishor38681 day ago
Pyhton Solution   
 def ispar(self,x):       l=[]       for i in range(len(x)):           if x[i] in '({[':               l.append(x[i])           if x[i]==')':               if len(l)==0:                   return False               if l[-1]=='(':                   l.pop()               else:                   return False           if x[i]=='}':               if len(l)==0:                   return False               if l[-1]=='{':                   l.pop()               else:                   return False           if x[i]==']':               if len(l)==0:                   return False               if l[-1]=='[':                   l.pop()               else:                   return False       if len(l)==0:           return True       else:           return False
0
bhardw022 days ago
Very simple python code:
def ispar(self,x):
        arr = [i for i in x]
        s=[]
        for i in range(0,len(arr),1):
            if arr[i] == '(' or arr[i] == '{' or arr[i] == '[':
                s.append(arr[i])
            elif arr[i] == ')':
                if len(s) == 0:
                    return False
                else:
                    top = s.pop()
                    if top != '(':
                        return False
            elif arr[i] == '}':
                if len(s) == 0:
                    return False
                else:
                    top = s.pop()
                    if top != '{':
                        return False
            elif arr[i] == ']':
                if len(s) == 0:
                    return False
                else:
                    top = s.pop()
                    if top != '[':
                        return False
        if len(s) >0:
            return False
        else:
            return True
0
ygoel852 days ago
    Python code: Time take(0.02 sec)
def ispar(self,x):
       # code here
       left='{(['
       right='})]'
       stack=[]
       for bracket in x:
           if bracket in left:
               stack.append(bracket)
           elif bracket in right:
               if(len(stack)==0):
                   return False
               if(right.index(bracket)!=left.index(stack.pop())):
                   return False
       
       if(len(stack)!=0):
           return False
       else:
           return True
0
protiks8903 days ago
def ispar(self,x):       # code here       while True:           if '{}' in x:               x=x.replace('{}','')           elif '()' in x:               x=x.replace('()','')           elif '[]' in x:               x=x.replace('[]','')           else:               return not x           
0
1912100293 days ago
bool ispar(string x)
{
    int n = x.length();
    stack<int> s;
    map<int, int> m = {
        { '(', 1 },
        { '[', 2 },
        { '{', 3 },
        { ')', -1 },
        { ']', -2 },
        { '}', -3 }
    };
    
    bool valid = true;
    for (char c : x) {
        if (m[c] > 0) s.push(m[c]);
        else if (!s.empty()) {
            int t = s.top();
            s.pop();
            if (t != -m[c]) {
                valid = false;
                break;
            }
        } else valid = false;
    }
    
    if (!s.empty()) valid = false;
    
    return valid;
}
+1
sunnychaware3 days ago
// utility function for checking if the 
// left and right paranthesis matches. 
bool match(char a, char b){
        
        if(a=='{' && b=='}' ||
        a=='(' && b==')' ||
        a=='[' && b==']')   return true;
        else return false;
    }
// main function
    bool ispar(string x)
    {
        if(x.length()&1)return false;
        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())return false;
                if(match(s.top(),x[i]))s.pop();
                else return false;
            }
        }
        if(!s.empty())return false;
        else return true;
    }
+1
takshat013 days ago
    bool ispar(string x)
   {
       // Your code here
       int len=x.length();
       if(len&1){
           return false;
       }
       
       stack<char> s;
       for(int i=0; i<len; i++){
           if(x[i]=='{' || x[i]=='[' || x[i]=='('){
               s.push(x[i]);
           }
           else if(!s.empty() &&((x[i]=='}' && s.top()=='{') || (x[i]==']' && s.top()=='[') || (x[i]==')' && s.top()=='('))){
               s.pop();
           }
           else{
               return false;
           }
       }
       
       if(s.empty()){
           return true;
       }
       
       return false;
   }
+1
thecodebuilder4 days ago
Approach -
Use a stack to store open braces and whenever the correct closing brace is encountered, pop from stack. If at last, stack is not empty, it means there is an extra opening or closing brace or order of braces is wrong. Thus, it is unbalanced.
 
Algo -
Traverse the given string character by character.
IF (stack is not empty) AND ((top element of stack is ‘(’ AND current string element is ‘)’) OR (top element of stack is ‘{’ AND current string element is ‘}’) OR (top element of stack is ‘[’ AND current string element is ‘]’)) pop the top element from stack, else push it to stack.
If stack is empty at end, return true else false.
Code -
bool ispar(string x)
   {
       // Your code here
       stack<char> st;
       for(int i=0;i<x.length();i++){
           if(!st.empty() && (( st.top() =='(' && x[i]==')' ) || ( st.top()=='{' && x[i]=='}' ) || ( st.top()=='[' && x[i]==']' )))
               st.pop();
                   
           else
               st.push(x[i]);
       }
       return st.empty()?true:false;
   }
 
0
byadwalnaveen12284 days ago
class Solution{   public:   //Function to check if brackets are balanced or not.   bool ispar(string x)   {       // Your code here      stack<char> temp;       for(int i=0;i<x.length();i++)       {           if(temp.empty())           {               temp.push(x[i]);           }           else if((temp.top()=='('&& x[i]==')')  ||  (temp.top()=='{' && x[i]=='}')  ||  (temp.top()=='[' && x[i]==']'))           {               temp.pop();           }           else           {               temp.push(x[i]);           }       }       if(temp.empty())       {           return true;       }       return false;                                     }
};
0
luvgupta76694 days ago
Simple Working Best Java Solution Using Stack | O(N)-
 
    static boolean ispar(String x) {
          Stack<Character> st = new Stack<>();
          for (int i=0; i< x.length(); i++) {
             char ch = x.charAt(i);
             if (ch == '{') {
               st.push('}');  
             } else if (ch == '[') { 
              st.push(']');  
             } else if (ch == '(') {
               st.push(')');  
             } else if (st.isEmpty() || st.pop()!=ch) {
               return false;
             }
          }
          return st.isEmpty();
    }
 
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.