Problem: https://www.hackerrank.com/challenges/balanced-brackets/problem

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, ].

Sample Code:


def check(str):
    lst=list()
    for i in range(len(str)):
        if str[i] in ('({[]})'):
            lst.append(str[i])
        if(len(lst)>1 and 
        ((lst[-2]=='[' and lst[-1]==']') //bracket type []
        or (lst[-2]=='{' and lst[-1]=='}') // bracket type {}
        or (lst[-2]=='(' and lst[-1]==')'))): // bracket type ()
            lst.pop()
            lst.pop()  

    if len(lst)==0:
        print('YES')
    else:
        print('NO')             

Explanation:

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top