Katkat

Validate Matching Brackets

ByteDanceSite Reliability Engineer · Technical Screen

Last 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:

  1. Open brackets are closed by the same type of brackets.
  2. Open brackets are closed in the correct order.
  3. 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 s of length n containing only '(', ')', '{', '}', '[', and ']'.
  • Output: A boolean (True or False).

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 be O(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 return True.
  • 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?