Solve Bracket Matching and Tree Width
Company: Bytedance
Role: Backend Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: HR Screen
Quick Answer: This composite question evaluates proficiency with core data structures and algorithmic reasoning, covering string-based bracket validation (sequence matching and nesting correctness) and binary-tree level-span computation using position indexing and attention to numerical robustness.
Part 1: Validate Balanced Brackets
Constraints
- 0 <= len(s) <= 100000
- s contains only the characters '(', ')', '{', '}', '[' and ']'.
Examples
Input: ""
Expected Output: True
Explanation: The empty string contains no unmatched brackets, so it is valid.
Input: "()[]{}"
Expected Output: True
Explanation: Each bracket is closed by the same type in the correct order.
Input: "([)]"
Expected Output: False
Explanation: The '[' bracket is opened after '(' but ')' tries to close '(' first, so the nesting order is invalid.
Input: "{[]}"
Expected Output: True
Explanation: The brackets are correctly nested.
Input: "((()"
Expected Output: False
Explanation: There are unmatched opening parentheses remaining.
Hints
- When you see an opening bracket, remember it until its matching closing bracket appears.
- The most recently opened bracket must be the first one closed.
Part 2: Compute the Maximum Level Span in a Binary Tree
Constraints
- 0 <= len(children) <= 100000
- If len(children) > 0, node 0 is the root.
- Each children[i] has exactly two integers: [left_child_index, right_child_index].
- Each child index is either -1 or an integer in the range [0, len(children) - 1].
- The input represents a valid binary tree: no cycles, no node has more than one parent, and all nodes are reachable from the root when non-empty.
- The solution should run in O(n) time.
- Avoid relying on unbounded raw position indexes growing with tree depth; normalize positions by level.
Examples
Input: []
Expected Output: 0
Explanation: The tree is empty, so there are no levels.
Input: [[-1, -1]]
Expected Output: 1
Explanation: A single-node tree has span 1 at its only level.
Input: [[1, 2], [3, -1], [-1, 4], [-1, -1], [-1, -1]]
Expected Output: 4
Explanation: At level 2, node 3 is at position 0 and node 4 is at position 3, giving span 3 - 0 + 1 = 4.
Input: [[1, -1], [2, -1], [3, -1], [-1, -1]]
Expected Output: 1
Explanation: The tree is a single left chain, so every level contains exactly one node.
Input: [[1, 2], [3, -1], [-1, 4], [5, -1], [-1, 6], [-1, -1], [-1, -1]]
Expected Output: 8
Explanation: At level 3, the leftmost node is at position 0 and the rightmost node is at position 7, so the span is 8.
Hints
- Use breadth-first search so you can process one level at a time.
- At each level, subtract the first node's position from all positions before generating child positions to keep numbers small.