Validate a bracket string
Company: Bytedance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of stack data structures, string parsing, and matching logic for balanced brackets and parentheses. It is commonly asked in technical interviews within the Coding & Algorithms domain to assess the ability to produce correct and efficient bracket-matching logic, testing practical application of data-structure implementation alongside conceptual understanding of stack behavior and edge-case handling.
Constraints
- 1 <= s.length <= 10^4 (the empty string is also considered valid).
- s consists only of the characters '(', ')', '{', '}', '[' and ']'.
Examples
Input: ("()[]{}",)
Expected Output: True
Explanation: Each opening bracket is immediately closed by a matching closing bracket of the same type.
Input: ("([)]",)
Expected Output: False
Explanation: The ')' tries to close '[', the most recent unmatched opener, so the order is wrong.
Input: ("",)
Expected Output: True
Explanation: An empty string has no unmatched brackets, so it is trivially valid.
Input: ("(",)
Expected Output: False
Explanation: The '(' is never closed; the stack is non-empty at the end.
Input: (")",)
Expected Output: False
Explanation: A closing bracket appears with no opener on the stack to match it.
Input: ("{[]}",)
Expected Output: True
Explanation: Properly nested: '[]' closes inside '{}'.
Input: ("([{}])",)
Expected Output: True
Explanation: Deeply nested brackets all close in the correct reverse order.
Input: ("]",)
Expected Output: False
Explanation: A lone closing bracket with an empty stack is invalid.
Input: ("((",)
Expected Output: False
Explanation: Two openers remain unmatched at the end, so the stack is not empty.
Hints
- Use a stack. Push every opening bracket as you encounter it.
- When you see a closing bracket, it must match the bracket on top of the stack — if the stack is empty or the top does not match, the string is invalid.
- After scanning the whole string, the string is valid only if the stack is empty (no unmatched openers remain).