Stacks · Easy
Valid parentheses
Input contains only ()[]{}. Return whether the brackets are balanced and correctly nested. Every closer must match the most recent opener that is still unmatched.
Worked example
'([])' → True
- Record ( and then [ as unmatched openers.
- ] matches [, then ) matches (. Nothing remains unmatched, so return True.
Python solution
def solve(brackets):
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for char in brackets:
if char not in pairs:
stack.append(char)
elif not stack or stack.pop() != pairs[char]:
return False
return not stackThe most recently opened bracket must be the first one closed.
Time: O(n) · Space: O(n)