Question presented to candidate: "Given a string that contains only the characters ( ) [ ] { }, write a Python function that returns True if every bracket is closed by the same kind of bracket in the correct order, and False otherwise. Talk me through the edge cases."
What a strong answer should cover:
- Use a stack because the most recently opened bracket must close first (last in, first out).
- The three failure cases: a closer with an empty stack, a closer that does not match the top, and openers left over at the end.
- O(n) time and O(n) space, with the early exit on odd length and on the first mismatch.
- Why a single counter only works for one bracket type: it cannot see order, so
([)]slips through. - Python specifics: a
listused as a stack withappend,popandstack[-1]; adictmapping closer to opener;stack.pop()on an empty list raisesIndexError, so checknot stackfirst.
Clarifying questions expected:
- "Can the string contain characters other than brackets?"
- "Should an empty string count as valid?"
Code / implementation expected: Yes โ a short Python function using a list as the stack and a dict of pairs.