Check whether brackets are balanced
Company: Walmart Labs
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's competency in string processing and bracket-matching concepts, testing familiarity with linear-time algorithms and simple data structures for recognizing correct nesting and matching of parentheses, brackets, and braces.
Constraints
- 0 <= len(s) <= 2 * 10^5
- The string may contain any characters
- Only the characters (), [], and {} are treated as brackets
Examples
Input: "(a[b]{c})"
Expected Output: True
Explanation: Ignoring letters, the bracket sequence is properly nested: ( [ ] { } ).
Input: "([)]"
Expected Output: False
Explanation: The `)` tries to close `(` while `[` is still open, so the order is invalid.
Input: "(("
Expected Output: False
Explanation: There are opening parentheses left unmatched at the end.
Input: ""
Expected Output: True
Explanation: An empty string has no unmatched brackets, so it is balanced.
Input: "abc123"
Expected Output: True
Explanation: There are no bracket characters, so nothing is unbalanced.
Input: "{[()]}!"
Expected Output: True
Explanation: The exclamation mark is ignored, and the brackets are correctly nested.
Input: "]"
Expected Output: False
Explanation: A closing bracket appears before any matching opening bracket.
Hints
- A stack is useful for tracking the most recent unmatched opening bracket.
- When you see a closing bracket, it must match the latest opening bracket that has not been closed yet.