Validate whether brackets are properly nested
Company: Bloomberg
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in sequence validation, paired-token matching, and the use of data structures to manage nested elements within strings.
Constraints
- 0 <= s.length <= 10^5
- s consists only of the characters '(', ')', '{', '}', '[', ']'
Examples
Input: "()"
Expected Output: true
Explanation: A single matched pair is valid.
Input: "()[]{}"
Expected Output: true
Explanation: Three independent matched pairs in sequence are all valid.
Input: "(]"
Expected Output: false
Explanation: '(' is closed by ']' which is the wrong type.
Input: "([)]"
Expected Output: false
Explanation: Brackets are interleaved, not properly nested: ')' tries to close '[' which is on top.
Input: "{[]}"
Expected Output: true
Explanation: Inner '[]' closes before the outer '{}' — correctly nested.
Input: ""
Expected Output: true
Explanation: Empty string is considered valid.
Input: "("
Expected Output: false
Explanation: Unmatched opening bracket remains on the stack at the end.
Input: ")"
Expected Output: false
Explanation: Closing bracket with nothing on the stack to match.
Input: "((()))"
Expected Output: true
Explanation: Deeply nested but balanced parentheses are valid.
Input: "([{}])"
Expected Output: true
Explanation: All three bracket types nested in matching order are valid.
Hints
- Process the string left to right and use a stack of open brackets.
- When you hit a closing bracket, it must match the most recently seen unmatched opening bracket — that is exactly the top of the stack.
- If the stack is empty when you see a closing bracket (or non-empty when the string ends), the string is invalid. You can return early on the first mismatch.