KatInterview

Equal Binary Digits and Ascending Tree Chain

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphstreesarraysprefix-sum

Last 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 nums is strictly 0 or 1

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.