Difficulty: Easy | Asked at: Microsoft, Meta, Bloomberg
Given a string containing just
(, ), {, }, [, ], determine if the input is valid. Brackets must close in the correct order.
Input: "{[()]}" → true
Input: "{[(])}" → false
Input: "(((" → false
💡 Hint: What data structure naturally handles "last opened, first closed"?
Solution:
python
def is_valid(s):
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in pairs.values():
stack.append(char)
elif char in pairs:
if not stack or stack.pop() != pairs[char]:
return False
else:
return False
return not stack
Complexity: O(n) time, O(n) space (worst case, all opening brackets).
Common mistake: Forgetting to check if the stack is empty at the very end.
"(((" never fails inside the loop - you only catch it because the stack still has unclosed brackets when you finish.Stacks show up constantly in interviews. Where else have you seen one used? 👇