Validate Nested Parentheses, Brackets, and Braces
OtherSoftware Engineer · Online AssessmentLast updated
Validate nested parentheses, brackets, and braces with correct handling of empty input, mismatched closing symbols, and unfinished groups.
A closing bracket must match the most recent opening bracket that has not yet been closed. Every opening bracket must eventually be closed.
Constraints & Assumptions
- This practice version uses the standard six-character bracket alphabet.
smay be empty; an empty string is valid.- The input contains at most 100,000 characters. This is a practice bound for choosing a linear algorithm.
- Adjacent complete groups are allowed:
()[]{}is valid. - Matching bracket counts alone are insufficient:
([)]is invalid.
Examples
- Input:
"{[()]}[]". Output:true. Both the nested group and the final pair close in the correct order. - Input:
"([)]". Output:false. The)appears while[is still the most recent unmatched opener.
Clarifying Questions to Ask
- Does the alphabet contain only brackets, or must other characters be ignored or rejected?
- Is the empty string valid?
- Is the input available at once, or must the same check work incrementally over chunks?
Hints
Hint 1
Remember the unfinished nesting: After reading a prefix, which unmatched opening bracket determines the only legal next closing bracket?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.