This problem follows the Stack Matching pattern, commonly found in the Stack category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Push opening brackets. Pop on closing bracket and check if they match.
A stack naturally handles nesting — the most recent opening bracket must match the next closing bracket, which is exactly LIFO order.
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in pairs:
if not stack or stack[-1] != pairs[char]:
return false
stack.pop()
else:
stack.push(char)
return len(stack) == 0Practice Valid Parentheses and similar Stack problems with flashcards. Build pattern recognition through active recall.
Practice this problem