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

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →