Skip to content
Programming101
Programmingoneonone

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programmingoneonone

Learn everything about programming

HackerRank Balanced Brackets solution

YASH PAL, 31 July 202410 September 2024

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("%dn", &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("%sn", 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);
});

coding problems solutions interview prepration kit

Post navigation

Previous post
Next post
  • Automating Image Format Conversion with Python: A Complete Guide
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
How to download udemy paid courses for free

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes