Validate Matching Brackets
ByteDanceSite Reliability Engineer · Technical ScreenLast updated
Tests stack-based parsing fundamentals, early mismatch detection, and linear-time string validation for balanced bracket sequences.
Validate Matching Brackets
In site reliability engineering, configuration validators and log processors often need to verify that structured expressions, such as queries, JSON snippets, or firewall rules, contain properly balanced brackets.
Write a function that takes a string s consisting solely of bracket characters ('(', ')', '{', '}', '[', ']') and returns True if the string is valid, and False otherwise.
A bracket sequence is considered valid if:
- Open brackets are closed by the same type of brackets.
- Open brackets are closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Function Signature
def is_valid_brackets(s: str) -> bool:
pass
Input and Output Format
- Input: A single string
sof lengthncontaining only'(',')','{','}','[', and']'. - Output: A boolean (
TrueorFalse).
Constraints
0 <= len(s) <= 10^5- The string contains only the six bracket characters:
(,),{,},[,]. - Time complexity should be
O(n)and auxiliary space complexity should beO(n).
Examples
Example 1:
Input: s = "{[()]}"
Output: True
Explanation: Each opening bracket is closed by the corresponding closing bracket in reverse order of appearance.
Example 2:
Input: s = "([)]"
Output: False
Explanation: The square bracket is closed before the inner parenthesis is closed, violating nesting order.
Example 3:
Input: s = "]"
Output: False
Explanation: There is no preceding opening bracket for the closing square bracket.
Edge Cases to Consider
- Empty string:
s = ""should returnTrue. - Odd-length string: Cannot be valid; can be short-circuited early.
- Unmatched opening brackets: For example,
s = "(((". - Unmatched closing brackets: For example,
s = ")".
Hints
Hint 1
A Last-In, First-Out (LIFO) stack naturally models the requirement that the most recently opened bracket must be the first one closed.
Hint 2
Use a hash map to associate each closing bracket with its expected opening bracket for constant-time lookup.
Hint 3
Be sure to check both the scenario where a closing bracket encounters an empty stack and the scenario where unclosed opening brackets remain on the stack at the end.
Follow-up questions
- How would you adapt your solution if the input contained arbitrary non-bracket characters, whitespace, or comments that need to be ignored?
- If the input stream is gigabytes in size and cannot fit entirely into memory, how would you process it and what is the memory footprint?
- How would you modify the function to return the 1-based character index of the first syntax error rather than just a boolean?
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.