KatInterview

Check Balanced Brackets and Find Tree Level Width

Stacks & QueuesAuto-graded · 23 test cases
HardAuto-gradedStacks & Queuesstackbfstree-traversal

Last updated

Tests stack-based matching for nested brackets and BFS position tracking to compute maximum horizontal distance in a binary tree.

You must solve two independent tasks and return both results:

Task 1: Bracket Balance Checker

Determine whether a string containing only bracket characters is properly balanced.

The input string contains only these six characters: (, ), [, ], {, }.

A string is valid if and only if:

  1. Every opening bracket is closed by a matching closing bracket of the same type
  2. Brackets close in the correct order: each closing bracket must match the most recently opened bracket that has not yet been closed
  3. No brackets remain unclosed at the end

Examples of valid strings: "", "()", "()[]{}", "([{}])", "{[()]}"

Examples of invalid strings: "(", "([)]", "]", "([)", "(()", "())", "(}"

Task 2: Binary Tree Maximum Width

Given a binary tree, compute the maximum width across all levels.

The tree is provided as a level-order array where null (or None) represents a missing node.

Width definition: The width of a level is the number of positions from the leftmost actual node to the rightmost actual node on that level, including all empty positions between them.

Position indexing: Assign positions to nodes as if building a complete binary tree:

  • The root node is at position 0
  • For any node at position i:
    • Its left child (if it exists) is at position 2 * i
    • Its right child (if it exists) is at position 2 * i + 1

Width calculation: For a level where the leftmost node is at position L and the rightmost node is at position R, the width is R - L + 1.

Example

Tree input: [1, 3, 2, 5, null, null, 9]

This represents:

      1           (position 0)
     / \
    3   2         (positions 0, 1)
   /     \
  5       9       (positions 0, 3)
  • Level 0: Only node 1 at position 0. Width = 0 - 0 + 1 = 1
  • Level 1: Nodes 3 and 2 at positions 0 and 1. Width = 1 - 0 + 1 = 2
  • Level 2: Nodes 5 and 9 at positions 0 and 3. Width = 3 - 0 + 1 = 4

Maximum width = 4

Input Specification

Your function receives two parameters:

  • s (str): A string containing only the six bracket characters, possibly empty
  • tree (List[Optional[int]] or None): Level-order array representation of the binary tree. None or an empty list represents an empty tree. null entries represent missing nodes.

Output Specification

Return a list with exactly two elements:

  1. A boolean: True if the bracket string is valid, False otherwise
  2. An integer: The maximum width of the tree, or 0 if the tree is empty

Constraints

  • 0 ≤ len(s) ≤ 10,000
  • 0 ≤ number of tree nodes ≤ 3,000
  • Tree node values are integers (values are not used in width calculation)
  • The input string s contains only the characters (, ), [, ], {, }
  • Position indices can grow very large in deep trees; your solution must handle this correctly

Examples

Example 1

Input: check_brackets_and_tree_width('()[]{}', [1, 3, 2, 5, None, None, 9])

Output: [True, 4]

Example 2

Input: check_brackets_and_tree_width('([{}])', [1, 3, 2, 5, None, None, 9])

Output: [True, 4]

Example 3

Input: check_brackets_and_tree_width('([)]', [])

Output: [False, 0]

Example 4

Input: check_brackets_and_tree_width('', None)

Output: [True, 0]

Hints

Hint 1

For brackets: a stack tracks unclosed opening brackets. When you see a closer, it must match the top of the stack.

Hint 2

For tree width: use BFS to process one level at a time. Track each node's position using the 2i and 2i+1 rule.

Hint 3

To avoid overflow with deep trees, subtract the leftmost position from all positions in a level before computing child positions. This keeps indices bounded.