Balanced Brackets HackerRank Solution

In this Balanced Brackets HackerRank solution, A bracket is considered to be any one of the following characters: (){}[, or ].

Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and ().

A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ].

By this logic, we say a sequence of brackets is balanced if the following conditions are met:

  • It contains no unmatched brackets.
  • The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets.

Given  strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO.

Function Description

Complete the function isBalanced in the editor below.

isBalanced has the following parameter(s):

  • string s: a string of brackets

Returns

  • string: either YES or NO

Input Format

The first line contains a single integer , the number of strings.
Each of the next  lines contains a single string , a sequence of brackets.

Constraints

  • , where  is the length of the sequence.
  • All chracters in the sequences ∈ { {, }, (, ), [, ] }.

Output Format

For each string, return YES or NO.

Sample Input

STDIN Function —– ——– 3 n = 3 {[()]} first s = ‘{[()]}’ {[(])} second s = ‘{[(])}’ {{[[(())]]}} third s ='{{[[(())]]}}’

Sample Output

YES
NO
YES

Explanation

  1. The string {[()]} meets both criteria for being a balanced string.
  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.

Balanced Brackets HackerRank solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

Problem Solution in JavaScript

function isBalanced(s) {
   
  let balanced=true;
   if(s.length%2!==0)
   balanced=false;
   
   let stack=[];
   for(let i=0;i<s.length;i++){
      if([']','}',')'].includes(s[i])){
          if(s[i]==='}'){
              if(stack.pop()!=='{'){
                  balanced=false;
                  break;
            }
          }
            else if(s[i]===']'){
              if(stack.pop()!=='['){
                  balanced=false;
                  break;
            }
            }
            else if(s[i]===')'){
              if(stack.pop()!=='('){
                  balanced=false;
                  break;
            }
            }
             
          }else{
               stack.push(s[i]);
          }
      }
      if(stack.length!==0)
      balanced=false;
   
   
   return balanced?"YES":"NO"


}

Problem Solution in Python

def isBalanced(s):
    pair = {'{': '}', '[': ']', '(': ')'}
    brackets = []
    for char in s:
        if char in pair.values():
            if not brackets or pair[brackets[-1]] != char:
                return 'NO'
            brackets.pop(-1)
        elif char in pair.keys():
            brackets.append(char)
           
    return 'NO' if brackets else 'YES'

Problem Solution in Java

public static String isBalanced(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put('[', ']');
        map.put('{', '}');
        map.put('(', ')');
       
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
           
            if (map.containsKey(c)) {
                stack.push(c);
            } else {
                if (!stack.empty() && (map.get(stack.peek()) == c)){
                    stack.pop();
                } else{
                    return "NO";
                }
            }            
        }
        return stack.empty() ? "YES" : "NO";


    }

Problem Solution in C#

public static string isBalanced(string s)
    {
        Stack<char> st = new Stack<char>();
       
        for(int i = 0 ; i <s.Length; i++)
        {
            if(s[i] == '(' || s[i] == '{' || s[i] == '[')
            {
                st.Push(s[i]);
            }
            else if (s[i] == ')')
            {
                if(st.Count > 0)
                {
                    char ch = st.Peek();
                    if(ch != '(')
                    {
                        return "NO";
                    }
                    else
                    {
                        st.Pop();    
                    }
                }
                else
                {
                    return "NO";
                }
            }
            else if (s[i] == '}')
            {
                if(st.Count > 0)
                {
                    char ch = st.Peek();
                    if(ch != '{')
                    {
                        return "NO";
                    }
                    else
                    {
                        st.Pop();    
                    }
                }
                else
                {
                      return "NO";
                }
            }
            else if (s[i] == ']')
            {
                if(st.Count > 0)
                {
                    char ch = st.Peek();
                    if(ch != '[')
                    {
                        return "NO";
                    }
                    else
                    {
                        st.Pop();    
                    }
                }
                else
                {
                    return "NO";
                }
               
            }
        }
       
        if(st.Count > 0)
        {
            return "NO";
        }
        else
        {
            return "YES";
        }
    }


}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems

Leave a Comment