Below mentioned problem is not a leetcode problem. This was one of the practice problems on Hackerrank.
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
Problem Statement - https://www.hackerrank.com/challenges/balanced-brackets/problem
Solution Approach
- Iterate over the given string.
- If you encounter an opening bracket "([{" push it to the stack.
- If you encounter a closing bracket pop the topmost element from the stack.
class Stack:
def __init__(self):
self.items = []
def push(self, element):
self.items.append(element)
def pop(self):
return self.items.pop()
def size(self):
length = len(self.items)
return length
def peek(self):
return self.items[len(self.items)-1]
def isBalanced(s):
stack = Stack()
result = True
for x in s:
if (x=='[') or (x=='(') or (x=='{'):
stack.push(x)
elif (x == ']') or (x == ')') or (x == '}'):
if stack.size() > 0:
topmost_element = stack.pop()
if ((topmost_element == '[') and (x != ']')) or ((topmost_element == '(') and (x != ')')) or ((topmost_element == '{') and (x != '}')):
result = False
break
if stack.size() == 0 and result:
return "YES"
else:
return "NO"
Alternate approaches to optimize the solution are welcome. No code snippets. Just discussion. :)
Top comments (1)
Disclaimer: If in case violates the requirements, please let me know
pop()
,append()
asO(1)
,{open:close}
. Which also hasO(1)
time complexity for accessing an element. e.g.if ((topmost_element == '[') and (x != ']')) or ((topmost_element == '(') and (x != ')')) or ((topmost_element == '{') and (x != '}')):
Thanks.