In this HackerRank Balanced Brackets Interview preparation kit problem you have Given n strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO.


HackerRank Balanced Brackets Interview preparation kit solution


Problem solution in Python programming.

#! /usr/bin/python3

def check():
    stack = []
    s = input()
    for c in s:
        #print(c)
        if c == '(':
            stack.append(0);
        elif c == ')':
            if len(stack) > 0 and stack[-1] == 0:
                stack.pop()
            else:
                return -1
        elif c == '[':
            stack.append(2)
        elif c == ']':
            if len(stack) > 0 and stack[-1] == 2:
                stack.pop()
            else:
                return -1
        if c == '{':
            stack.append(4)
        elif c == '}':
            if len(stack) > 0 and stack[-1] == 4:
                stack.pop()
            else:
                return -1
    
    if len(stack) == 0:
        return 0
    else:
        return -1

def solve():
    t = int(input())
    for i in range(0,t):
        if check() == 0:
            print("YES")
        else:
            print("NO")
solve()            
                    




Problem solution in Java Programming.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        try{
          int numTest = Integer.parseInt(sc.nextLine());
          for(int i = 0; i < numTest; i++){
              
           if(isBalanced(sc.nextLine())){
               System.out.println("YES");
           } else {
               System.out.println("NO");
           }
          }
        } catch(Exception e){
            System.out.println("Invalid Input");
        }
    }
    public static boolean isBalanced(String s){
        if(s == null || s.length() % 2 != 0) return false;
        Stack<Character> stack = new Stack<Character>();
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if(c == '(' || c == '{' || c == '['){
                stack.push(c);
            } else if(c == ')' || c == '}' || c == ']'){
                if(!stack.isEmpty()){
                    char latestOpenP = stack.pop();
                    if(latestOpenP == '(' && c != ')'){
                        return false;
                    } else if(latestOpenP == '{' && c != '}'){
                        return false;
                    } else if(latestOpenP == '[' && c != ']'){
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
    
        return stack.isEmpty();
    }
}


Problem solution in C++ programming.

#include <bits/stdc++.h>

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;
}


Problem solution in C programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define MAX_SIZE 1000

struct stack {
    char stk[MAX_SIZE];
    int top;
} s;

void push(char c) {
    if (s.top < MAX_SIZE) {
        s.stk[++s.top] = c;
    }
}

char pop() {
    if (s.top > -1) {
        return  s.stk[s.top--];
    } else {
        return -1;
    }
}

int balancedParentheses(char *s, int length) {
    char target, c;
    if (length % 2 != 0) {
        return 0;
    }
    for(int i = 0; i < length; i++) {
        if ((s[i]=='(') || (s[i]=='{') || (s[i]=='[')) {
            push(s[i]);
        } else {
            switch(s[i]) {
                case ')': target = '('; break;
                case '}': target = '{'; break;
                case ']': target = '['; break;
            }
            c = pop();
            if (c == -1 || c != target) {
                return 0;
            }
        }
    }
    return pop() == -1;
}

int main() {
    int t, length;
    char str[1000], c;
    scanf("%d\n", &t);
    for (int i = 0; i < t; i++) {
        s.top = -1;
        length = 0;
        for (;;) {
            c = getchar();
            if (c == EOF || c == '\n') {
                break;
            }
            str[length] = c;
            length++;
        }
        printf("%s\n", balancedParentheses(str, length) == 0 ? "NO" : "YES");
    }
    return 0;
}


Problem solution in JavaScript programming.

function processData(input) {
    //Enter your code here
    
    var res = '', tempStr;
    
    testArr = input.split('\n').slice(1);
    
    //console.log(testArr);
    
    main: for (var i = 0; i < testArr.length; i++) {
    
        var string = testArr[i];
        tempStr = '';
        
        for (var j = 0; j < string.length; j++) {
            
            switch (string[j]) {
                case ')' :
                    if (tempStr && tempStr.slice(-1) === '(') {
                        tempStr = tempStr.slice(0, -1);
                        break;
                    } else {
                        no();
                        continue main;
                    };
                case '}' :
                    if (tempStr && tempStr.slice(-1) === '{') {
                        tempStr = tempStr.slice(0, -1);
                        break;
                    } else {
                        no();
                        continue main;
                    };
                case ']' :
                    if (tempStr && tempStr.slice(-1) === '[') {
                        tempStr = tempStr.slice(0, -1);
                        break;
                    } else {
                        no();
                        continue main;
                    };
                default: tempStr += string[j];
            }
            
            //console.log(tempStr);

        };
        
        if (!tempStr) {
            yes();
        } else {
            no();
        }
        
    };
    
    
    function yes() {
        res += 'YES' + '\n';
    }
    
    function no() {
        res += 'NO' + '\n';
    }
    
    console.log(res.trim());
    
    
    
    
    
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});