We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Data Structures
  3. Stacks
  4. Balanced Brackets
  5. Discussions

Balanced Brackets

Problem
Submissions
Leaderboard
Discussions
Editorial

Sort 1431 Discussions, By:

votes

Please Login in order to post a comment

  • parasou79
    4 years ago+ 48 comments

    Without using stack

    let n = -1;
    	while (s.length != n) {
    		n = s.length;
    		s = s.replace('()', '');
    		s = s.replace('[]', '');
    		s = s.replace('{}', '');
    	}
    	if (s.length == 0)
    		return "YES"
    	else 
    		return "NO"
    
    227|
    Permalink
    View more Comments..
  • alexYer
    6 years ago+ 19 comments

    C++ solution.

    #include <stack>
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    string isBalanced(string s) {
        stack<char> st;  
        
        for (auto c: s) {
            switch (c) {
                case '{':
                case '(':
                case '[':
                    st.push(c);
                    break;
                case '}':
                    if (st.empty() || (st.top() != '{')) {
                        return "NO";
                    }
                    st.pop();
                    break;
                case ')':
                    if (st.empty() || (st.top() != '(')) {
                        return "NO";
                    }
                    st.pop();
                    break;
                case ']':
                    if (st.empty() || (st.top() != '[')) {
                        return "NO";
                    }
                    st.pop();
                    break;
            }
        }
        
        return st.empty() ? "YES" : "NO";
    }
    
    
    int main(){
        int t;
        cin >> t;
        for(int a0 = 0; a0 < t; a0++){
            string s;
            cin >> s;
            cout << isBalanced(s) << endl;
        }
        return 0;
    }
    
    87|
    Permalink
    View more Comments..
  • w00tles
    6 years ago+ 10 comments

    Python solution

    lefts = '{[('
    rights = '}])'
    closes = { a:b for a,b in zip(rights,lefts)}
    
    def valid(s):
        stack = []
        for c in s:
            if c in lefts:
                stack.append(c)
            elif c in rights:
                if not stack or stack.pop() != closes[c]:
                    return False
        return not stack  # stack must be empty at the end
    
    t = int(raw_input().strip())
    for a0 in xrange(t):    
        s = raw_input().strip()    
        if valid(s):
            print 'YES'
        else:
            print 'NO'
    
    49|
    Permalink
    View more Comments..
  • adi0507890220
    2 years ago+ 8 comments
    def isBalanced(s):
        restart=True
        while restart:
            if '{}' in s:
                s=s.replace('{}','')
            elif '()' in s:
                s=s.replace('()','')
            elif '[]' in s:
                s=s.replace('[]','')
            else:
                restart=False
        return 'YES' if len(s)==0 else 'NO'
    
    46|
    Permalink
    View more Comments..
  • sanju1
    5 years ago+ 3 comments

    solution using stacks all test cases passed!

    public boolean isValid(String s){
            Stack<Character> stack=new Stack<Character>();
            for(char c:s.toCharArray()){
                if(c=='(')
                    stack.push(')');
                else if(c=='{')
                   stack.push('}');
                   else if(c=='[')
                   stack.push(']');
                   else if(stack.isEmpty()||stack.pop()!=c)
                   return false;
            }
                   return stack.isEmpty();
        }
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int t = in.nextInt();
            for(int a0 = 0; a0 < t; a0++){
                String s = in.next();
                    System.out.println(isValid(s) ? "YES":"NO");
            }
        }
    
    27|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature