Posted on:

16 May 2023

0

This is how i solved it

It basically looks at the mirrored version of an element and then pushes it into an array that need to be half the size of the original to be considered balanced (it actually doesnt use stacks):

str=input('Enter the brackets>> ')
br_list=[]
for br in str:
    br_list.append(br)

br_stack=[]
i=0
while i<len(br_list)/2:
    el=br_list[i]
    reverse_el=br_list[len(br_list)-i-1]
    if((el=='{' and reverse_el=='}') or (el=='[' and reverse_el==']')
       or (el=='(' and reverse_el==')')):
        br_stack.append(el)  
    i=i+1
if(len(br_stack)==len(br_list)/2):
    print('Balanced')
else:
    print('Not Balanced')

0 answers ( 0 marked as helpful)

Submit an answer