Check Balanced Brackets and Find Tree Level Width
Stacks & QueuesAuto-graded · 23 test casesLast 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:
- Every opening bracket is closed by a matching closing bracket of the same type
- Brackets close in the correct order: each closing bracket must match the most recently opened bracket that has not yet been closed
- 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
- Its left child (if it exists) is at position
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 emptytree(List[Optional[int]] or None): Level-order array representation of the binary tree.Noneor an empty list represents an empty tree.nullentries represent missing nodes.
Output Specification
Return a list with exactly two elements:
- A boolean:
Trueif the bracket string is valid,Falseotherwise - An integer: The maximum width of the tree, or
0if the tree is empty
Constraints
0 ≤ len(s) ≤ 10,0000 ≤ number of tree nodes ≤ 3,000- Tree node values are integers (values are not used in width calculation)
- The input string
scontains 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Check Balanced Brackets and Find Tree Level Width
This problem combines two fundamental algorithmic patterns: stack-based validation for nested structures and breadth-first traversal with indexing for tree measurement.
Part 1: Bracket Balance Validation
Approach
Brackets must close in the reverse order they open, which maps perfectly to stack behavior (last-in, first-out).
Algorithm:
- Iterate through each character in the string
- For an opening bracket (
(,[,{): push it onto a stack - For a closing bracket (
),],}):- Check if the stack is empty or the top element doesn't match — if so, return
False - Otherwise, pop the matching opener from the stack
- Check if the stack is empty or the top element doesn't match — if so, return
- After processing all characters, return
Trueif the stack is empty,Falseotherwise
Use a dictionary mapping each closing bracket to its corresponding opener for O(1) matching.
Why This Works
The stack holds all currently open brackets in the order they were opened. When we encounter a closing bracket, it must match the most recently opened bracket (the stack top). If every closer finds its match and no openers remain at the end, the string is valid. Any violation is detected immediately when it occurs.
Complexity
- Time: O(n) where n is the string length. Each character is processed once with O(1) operations.
- Space: O(n) worst case, when all characters are opening brackets.
Part 2: Maximum Tree Width
Approach
Position nodes as if the tree were complete: root at index 0, left child of node at index i at 2i, right child at 2i + 1. The width of any level is then rightmost_index - leftmost_index + 1, automatically accounting for gaps.
Algorithm using BFS:
- Use a queue storing
(node, position_index)pairs - Process one complete level at a time
- For each level:
- Record the leftmost and rightmost indices from the first and last queue entries
- Calculate width and update the maximum
- Enqueue children with their calculated positions
- Crucial: Before computing child positions, subtract the leftmost index from all positions on that level (normalization) to prevent exponential index growth
Why This Works
The position indexing creates a one-to-one mapping to positions in a complete binary tree. Two nodes at indices a and b on the same level have exactly b - a gaps between them, so the span b - a + 1 counts both endpoints and all positions between. BFS processes levels in order and nodes left-to-right (since we enqueue left children before right), guaranteeing the first and last queue entries are the extreme positions.
Normalization keeps indices small without changing widths, since width depends only on the difference between indices. This prevents overflow in fixed-integer languages and keeps arithmetic fast in Python.
Complexity
- Time: O(n) where n is the number of nodes. Each node is enqueued and dequeued once.
- Space: O(w) where w is the maximum number of nodes on any level. Worst case O(n) for a nearly complete tree.
Edge Cases
Brackets:
- Empty string
"": valid (no unmatched brackets) - Only openers
"(((": invalid (stack non-empty at end) - Starts with closer
")(": invalid (empty stack when closer arrives) - Wrong pairing
"([)]": invalid ()finds[on top)
Tree:
Noneor[]: width is 0- Single node: width is 1
- Skewed tree (all left or all right): width is 1 at every level
- Widest level not at bottom: maximum is correctly tracked across all levels
Complete Solution
from collections import deque
from typing import List, Optional, Union
class TreeNode:
def __init__(self, val: int = 0, left: Optional['TreeNode'] = None, right: Optional['TreeNode'] = None):
self.val = val
self.left = left
self.right = right
def _validate_brackets(s: str) -> bool:
"""Validate bracket string using stack."""
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in pairs: # closing bracket
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
else: # opening bracket
stack.append(ch)
return len(stack) == 0
def _build_tree_from_array(arr: List[Optional[int]]) -> Optional[TreeNode]:
"""Construct tree from level-order array."""
if not arr or arr[0] is None:
return None
root = TreeNode(arr[0])
q = deque([root])
idx = 1
while q and idx < len(arr):
node = q.popleft()
if idx < len(arr) and arr[idx] is not None:
node.left = TreeNode(arr[idx])
q.append(node.left)
idx += 1
if idx < len(arr) and arr[idx] is not None:
node.right = TreeNode(arr[idx])
q.append(node.right)
idx += 1
return root
def _calculate_max_width(root: Optional[TreeNode]) -> int:
"""Calculate maximum width using BFS with position tracking."""
if root is None:
return 0
result = 0
q = deque([(root, 0)])
while q:
size = len(q)
first_pos = q[0][1]
last_pos = q[-1][1]
result = max(result, last_pos - first_pos + 1)
for _ in range(size):
node, pos = q.popleft()
# Normalize position to prevent overflow
pos = pos - first_pos
if node.left:
q.append((node.left, 2 * pos))
if node.right:
q.append((node.right, 2 * pos + 1))
return result
def check_brackets_and_tree_width(s: str, tree: List[Optional[int]]) -> List[Union[bool, int]]:
"""
Check if brackets are balanced and compute maximum tree width.
Args:
s: String with only bracket characters: ( ) [ ] { }
tree: Level-order tree array (None values for missing nodes)
Returns:
[is_balanced, max_width] - boolean and integer
"""
root = _build_tree_from_array(tree)
return [_validate_brackets(s), _calculate_max_width(root)]
Tracing the example:
Input: s = "()[]{}", tree = [1, 3, 2, 5, null, null, 9]
Brackets: Stack operations validate each pair correctly → True
Tree levels:
- Level 0: position 0 → width 1
- Level 1: positions 0, 1 → width 2
- Level 2: positions 0, 3 → width 4
Result: [True, 4]