Check balanced parentheses with multiple bracket types
Company: Snowflake
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in stack-based parsing, string manipulation, and algorithmic reasoning for correctly matching and nesting multiple bracket types, and belongs to the Coding & Algorithms domain.
Constraints
- 0 <= len(s) <= 10^4
- s may contain the characters ()[]{} and possibly other characters
- Any character outside the six bracket characters makes the string invalid (not balanced)
- The empty string is balanced
Examples
Input: ("()",)
Expected Output: True
Explanation: A single matched pair of round parentheses is balanced.
Input: ("()[]{}",)
Expected Output: True
Explanation: Three independent matched pairs of different types, each opened and closed correctly.
Input: ("(]",)
Expected Output: False
Explanation: An opening '(' is closed by ']', a mismatched bracket type.
Input: ("([)]",)
Expected Output: False
Explanation: Brackets close in the wrong order: ')' appears while '[' is still open, violating LIFO nesting.
Input: ("{[]}",)
Expected Output: True
Explanation: Correctly nested: '[]' is fully closed inside the outer '{}'.
Input: ("",)
Expected Output: True
Explanation: The empty string has no unmatched brackets, so it is balanced.
Input: ("(",)
Expected Output: False
Explanation: A lone opening parenthesis is never closed; the stack is non-empty at the end.
Input: (")",)
Expected Output: False
Explanation: A closing parenthesis with no opening bracket on the stack.
Input: ("((()))",)
Expected Output: True
Explanation: Deeply nested round parentheses that all match in correct order.
Input: ("a(b)c",)
Expected Output: False
Explanation: Contains non-bracket characters 'a', 'b', 'c', which are treated as invalid input.
Hints
- Use a stack: push every opening bracket as you scan left to right.
- When you hit a closing bracket, the top of the stack must be the matching opening bracket of the same type; otherwise the string is unbalanced.
- After scanning the whole string, the stack must be empty — leftover opening brackets mean it is unbalanced. Also reject any character that is not one of ()[]{}.