Balanced Brackets


Problem Statement :


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 n 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. It must return a string: YES if the sequence is balanced or NO if it is not.

isBalanced has the following parameter(s):

s: a string of brackets

Input Format

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


Output Format

For each string, return YES or NO.



Solution :



title-img


                            Solution in C :

In   C :





#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int same(char a,char b)
    {
    if(a=='['&& b==']')
        return 1;
    if(a=='{'&& b=='}')
        return 1;
    if(a=='('&& b==')')
        return 1;
    return 0;
}
int check(char *a)
    {
    char stack[1001],top=-1;
        for(int j=0;j<strlen(a);j++)
            {
         if(a[j]=='['||a[j]=='{'||a[j]=='(')
              stack[++top]=a[j]; 
           if(a[j]==']'||a[j]=='}'||a[j]==')')
               {
               if(top==-1)
                   {
               return 0;
               }
               else
                   {
                   if(!same(stack[top--],a[j]))
                       {
               return 0;
               }
           }
        } 
}
    if(top!=-1)
                {
               return 0;
            }
    return 1;
}
int main() {
char a[1001];
    int n,valid;
    scanf("%d",&n);
     for(int i=0;i<n;i++)
        {
     scanf("%s",a);
         valid = check(a);
         if(valid==1)
             printf("YES\n");
    else
        printf("NO\n");
     }
    return 0;
}
                        


                        Solution in C++ :

In   C ++ :




#include <cmath>
#include <cstdio>
#include <stack>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
     
    int t,i;
    string s;
    stack<char>a;
    cin>>t;
    while(t--){
        cin>>s;
        for(i=0;i<s.size();i++){
            if(s[i]=='(')
                a.push(s[i]);
            else if(s[i]=='{')
                a.push(s[i]);
            else if(s[i]=='['){
                a.push(s[i]);
            }
            else if(s[i]==')'){
                if(!a.empty()){
                if(a.top()=='(')
                    a.pop();
                else 
                    break;
                }
                else
                    break;
            }
            else if(s[i]=='}'){
                if(!a.empty()){
                    if(a.top()=='{')
                    a.pop();
                else 
                    break;
                }
                else
                    break;
            }
            else if(s[i]==']'){
                if(!a.empty()){
                if(a.top()=='[')
                    a.pop();
                else 
                    break;
                }
                else
                    break;
            }
        }
        
        if(a.empty()&&i==s.size())
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
        while(!a.empty()){
            
            a.pop();
        }
    }
    return 0;
}
                    


                        Solution in Java :

In    Java  :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
     
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        //int arr[] = new int[n];
        for(int arr_i=0; arr_i < n; arr_i++){
            Stack st = new Stack();
            //arr[arr_i] = in.nextInt();
            String ipSeq = in.next();
            //System.out.println(ipSeq);
            boolean match = true;
            for(int ind=0; ind<ipSeq.length(); ind++){
                char ch = ipSeq.charAt(ind);
                if(ch=='(' || ch=='{' || ch=='['){
                    st.push(ch);
                }else if(st.isEmpty()){
                    match = false;
                    break;
                }else if(ch==')'){
                    if('('!=(char)st.pop()){
                        match = false;
                        break;
                    }
                }else if(ch=='}'){
                    if('{'!=(char)st.pop()){
                        match = false;
                        break;
                    }
                }else if(ch==']'){
                    if('['!=(char)st.pop()){
                        match = false;
                        break;
                    }
                }
            }

            if(match){
                if(!st.isEmpty()){
                    System.out.println("NO");
                }else{
                    System.out.println("YES");
                }
            }else{
                System.out.println("NO");
            }
        }
    }
}
                    


                        Solution in Python : 
                            
In   Python3 :






t = int(input())
while t:
    ar = ['e']
    s = input()
    for i in s:
        if i == '(':
            ar.append('(')
        elif i == '[':
            ar.append('[')
        elif i == '{':
            ar.append('{')
        elif i == ')':
            k = ar.pop()
            if k != '(':
                ar.append('k')
                break
        elif i == ']':
            k = ar.pop()
            if k != '[':
                ar.append('k')
                break
        elif i == '}':
            k = ar.pop()
            if k != '{':
                ar.append('k')
                break
        #print(ar)
    if len(ar) == 0 or ar[len(ar)-1] != 'e':
        print('NO')
    else:
        #print(len(ar), ar[len(ar)-1])
        print('YES')
    t-=1
                    


View More Similar Problems

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →