Skip to content

Instantly share code, notes, and snippets.

@wilfreddesert
Created February 11, 2021 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilfreddesert/2984f0a0087adac3dee6d25c1bfbf7f2 to your computer and use it in GitHub Desktop.
Save wilfreddesert/2984f0a0087adac3dee6d25c1bfbf7f2 to your computer and use it in GitHub Desktop.
def is_balanced(exp: AnyStr) -> bool:
"""
Time Complexity: O(n)
Space complexity: O(n)
>>> s = "()[]{}"
>>> is_balanced(s)
True
>>> s = "([)]"
>>> is_balanced(s)
False
>>> s = "{[]}"
>>> is_balanced(s)
True
>>> s = "()"
>>> is_balanced(s)
True
"""
opening = ["(", "[", "{"]
closing = [")", "]", "}"]
mapping = dict(zip(closing, opening))
stack = []
for char in exp:
if char in closing:
if not stack or stack[-1] != mapping[char]:
return False
stack.pop()
else:
stack.append(char)
return not stack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment