Equal Binary Digits and Ascending Tree Chain
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests prefix-sum balancing for binary arrays and depth-first search for strictly increasing root-to-leaf paths in binary trees.
You must solve two independent problems and return both results.
Problem 1: Maximum Equal-Binary Subarray Length
You receive an array nums where every element is either 0 or 1. Find the length of the longest contiguous subarray containing an equal count of 0s and 1s.
Input: nums – a list of integers, each either 0 or 1
Output: an integer representing the maximum subarray length with equal 0s and 1s
Problem 2: Longest Strictly Ascending Path from Root
You receive a binary tree encoded as a level-order list (with None marking missing children). Find a path that starts at the root, follows parent-to-child edges, and is strictly increasing (each child value must exceed its parent value). Return the node values along the longest such path.
If multiple paths tie for maximum length, return any one.
Input: tree – a level-order list representing a binary tree, or None/empty
Output: a list of integers representing the values along the chosen maximum-length strictly increasing path starting from the root
Combined Interface
Your function receives both inputs and returns a two-element list: [max_length, path_values].
Constraints
- Array length:
1 ≤ len(nums) ≤ 200,000 - Tree nodes:
0 ≤ node_count ≤ 200,000 - Node values: any integer (may be negative)
- Each element in
numsis strictly0or1
Examples
Example 1
Input: solve_both([0, 1], [5, 3, 8, 2, 4, 7, 9])
Output: [2, [5, 8, 9]]
Example 2
Input: solve_both([0, 0, 1, 0, 1, 1], [1, 2, 3, 4, 5, 6, 7])
Output: [6, [1, 2, 4]]
Example 3
Input: solve_both([1], None)
Output: [0, []]
Hints
Hint 1
For the array problem, transform 0→-1 and 1→+1 and track running sums. Equal counts mean the sum returns to a previous value.
Hint 2
Store only the first occurrence of each prefix sum. The earliest match gives the longest subarray.
Hint 3
For the tree problem, build the tree from the level-order list using a queue, then traverse downward only through edges where the child value strictly exceeds the parent.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1: Equal Binary Subarray
Transform the problem by mapping 0 → -1 and 1 → +1, then compute a running prefix sum (called the balance). A subarray from index j+1 to i has equal 0s and 1s exactly when balance[i] == balance[j].
Use a hash map to record the first occurrence of each balance value, initializing with {0: -1} to handle subarrays starting at index zero. For each position, check if the current balance has been seen before. If so, compute the subarray length; if not, store this as the first occurrence. Track the maximum length encountered.
Why it works: Every balanced subarray corresponds to two positions with identical prefix sums. To maximize length for a fixed right endpoint, we need the leftmost position with that sum, which is exactly what storing first occurrences gives us.
Time complexity: O(n) – single pass through the array
Space complexity: O(n) – the hash map can hold up to 2n+1 distinct balance values
Part 2: Ascending Root Path
First, reconstruct the binary tree from the level-order list using a queue. Each non-null node dequeued consumes two list positions for its left and right children.
Then perform an iterative depth-first search starting from the root. Only follow edges where the child value strictly exceeds the parent value. Track each node's parent and depth. Record the deepest node reached (using strict comparison so the first deepest node wins). Finally, reconstruct the path by walking parent pointers back to the root and reversing.
Why it works: The DFS visits every node reachable via strictly increasing edges from the root. The deepest such node defines the longest increasing root path. Using iteration avoids stack overflow on deep trees with up to 200,000 nodes.
Time complexity: O(n + m) where n is the number of tree nodes and m is the length of the input list
Space complexity: O(n) for the tree structure, parent map, and DFS stack
Code
from typing import List, Optional
from collections import deque
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def solve_both(nums: List[int], tree: Optional[List[Optional[int]]]) -> List[object]:
# Problem 1: longest subarray with equal 0s and 1s
first_seen = {0: -1}
balance = 0
max_length = 0
for i, value in enumerate(nums):
balance += 1 if value == 1 else -1
if balance in first_seen:
max_length = max(max_length, i - first_seen[balance])
else:
first_seen[balance] = i
if not tree or tree[0] is None:
return [max_length, []]
# Build tree from level-order list
root = TreeNode(tree[0])
queue = deque([root])
index = 1
while queue and index < len(tree):
node = queue.popleft()
if index < len(tree) and tree[index] is not None:
node.left = TreeNode(tree[index])
queue.append(node.left)
index += 1
if index < len(tree) and tree[index] is not None:
node.right = TreeNode(tree[index])
queue.append(node.right)
index += 1
# Problem 2: longest strictly increasing path from root
parent_map = {root: None}
deepest_node, max_depth = root, 0
stack = [(root, 1)]
while stack:
node, depth = stack.pop()
if depth > max_depth:
max_depth, deepest_node = depth, node
for child in (node.right, node.left):
if child is not None and child.val > node.val:
parent_map[child] = node
stack.append((child, depth + 1))
path_values = []
current = deepest_node
while current is not None:
path_values.append(current.val)
current = parent_map[current]
path_values.reverse()
return [max_length, path_values]