Balanced Brackets Hackerrank Solution

For Example: Given an expression string s. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in s.
For example, the program should print ‘YES’ for s = “[()]{}{[()()]()}” and ‘NO’ for s = “[(])”

Sample Input

3
{[()]}
{[(])}
{{[[(())]]}}

Sample Output

YES
NO
YES

Explanation

  1. The string {[()]} meets both criteria for being a balanced string, so we print YES on a new line.
  2. The string {[(])} is not balanced because the brackets enclosed by the matched pair { and } are not balanced: [(]).
  3. The string {{[[(())]]}} meets both criteria for being a balanced string, so we print YES on a new line.

We will use stack here to solve this problem

We have to Complete isBalanced function..

Code:

static String isBalanced(String s) {
        Stack<Character> str = new Stack();
        String ans = "YES";
        String no = "NO";
        boolean answer = true;
        for(int i=0; i<s.length(); i++){
            char ch = s.charAt(i);
            if(ch == '{' || ch == '[' || ch == '('){
                str.push(ch);
                continue;
            }
            if(str.isEmpty()){
                return no;

            }
            if(ch == ')'){
                if(str.peek() == '('){
                    str.pop();
                }else{
                    answer = false;
                    break;
                }
            }
            if(ch == ']'){
                if(str.peek() == '['){
                    str.pop();
                }else{
                    answer = false;
                    break;
                }
            }
            if(ch == '}'){
                if(str.peek() == '{'){
                    str.pop();
                }else{
                    answer = false;
                    break;
                }
            }
            

        }
        if(!str.isEmpty()){
                answer = false;
            }
            if(answer)
            return ans;
            else
            return no;


    }

Thank You!

Happy Coding Friends!

2 thoughts on “Balanced Brackets Hackerrank Solution

Leave a comment