Binary Tree Depth and Room Scheduling
Hard · Coding & Algorithms · Data Scientist · Onsite
Problem Statement
Implement tree_depth_and_meeting_rooms(children, intervals), which solves two independent tasks and returns a two-element list [max_depth, min_rooms]:
-
Binary tree node depth (
children):- When
childrenis empty ([]), the tree contains no nodes andmax_depthis0. - When
childrenhas lengthn > 0, the tree containsnnodes numbered0throughn - 1, with node0as the root. Entrychildren[i] = [left, right]lists the left and right child indices of nodei, using-1when no child exists on that side. max_depthis the largest count of nodes along any downward path from root0to a leaf node ([-1, -1]). Trees may be severely skewed (such as a single chain of100,000nodes), so your traversal must avoid overflowing the call stack.
- When
-
Peak room allocation (
intervals):- Each element
[start, end]inintervalsrepresents a session spanning the half-open integer window[start, end), meaning it occupies timestwithstart <= t < end. - No two overlapping sessions may occupy the same room. Because the upper bound
endis exclusive, a session ending at timestamptfrees its room just in time for a session starting attto use the same room. min_roomsis the smallest number of rooms needed to accommodate every session (0ifintervalsis empty).
- Each element
Examples
Example 1
Input:
children = [[1, 2], [3, -1], [-1, 4], [-1, 5], [-1, -1], [-1, -1]]
intervals = [[2, 12], [4, 8], [6, 11], [9, 14]]
Output: [4, 3]
Root 0 links to 1 on the left and 2 on the right. The left branch 0 -> 1 -> 3 -> 5 contains 4 nodes, beating the right branch 0 -> 2 -> 4 (3 nodes), so max_depth = 4. Among the sessions, [2, 12), [4, 8), and [6, 11) overlap during [6, 8) and require 3 rooms; once [4, 8) ends at 8, [9, 14) reuses that freed room, keeping min_rooms = 3.
Example 2
Input:
children = [[-1, 1], [-1, -1]]
intervals = [[1, 6], [6, 9], [9, 15]]
Output: [2, 1]
Root 0 has a single right child 1, giving path 0 -> 1 of length 2 nodes. The three sessions [1, 6), [6, 9), and [9, 15) touch only at their endpoints (6 and 9); under half-open semantics each finishing session hands its room directly to the next, so 1 room suffices.
Constraints
0 <= len(children) <= 100,000- If
len(children) > 0, node0is the root, eachchildren[i]has two integers[left, right]in{-1, 1, ..., len(children) - 1}, and the links form a valid binary tree. 0 <= len(intervals) <= 100,000- Every interval
[start, end]contains integers satisfying-10^9 <= start < end <= 10^9.
Step-by-step walkthrough
Understand both tasks and input shapes
This function solves two independent problems and returns
[depth, rooms]:- Binary tree node depth (
children):- Nodes are numbered
0throughn - 1, with node0as the root (the top node) whenever the tree is non-empty. An empty list[]represents an empty tree (depth0). children[i] = [left_child, right_child]stores the indices of nodei's two children, using-1to mean "no child".- Depth counts nodes (not edges) along the longest path from the root down to a leaf (a node whose children are both
-1).
- Nodes are numbered
Example 1 children: [[1, 2], [3, -1], [-1, 4], [-1, 5], [-1, -1], [-1, -1]] Index: 0 1 2 3 4 5 Links: [1, 2] [3, -1] [-1, 4] [-1, 5] [-1, -1] [-1, -1] Tree: 0 <-- Layer 1 (root) / \ 1 2 <-- Layer 2 / \ 3 4 <-- Layer 3 \ 5 <-- Layer 4 (deepest leaf) => depth = 4- Minimum rooms (
intervals):- Each interval
[start, end]represents a half-open interval[start, end)— it occupies timestwherestart <= t < end. - Because
endis excluded, a session[1, 6)vacates its room right at timestamp6, so[6, 9)can reuse that exact same room (1room total).
- Each interval
Both inputs can have up to
100,000items, which rules outO(n^2)scans and deep recursion in Python.- Binary tree node depth (
Subproblem 1: Why plain recursion fails on skewed trees
The textbook formula for tree depth is
1 + max(depth(left), depth(right)), returning0when a child is-1. While mathematically valid, recursion pauses each unfinished parent call on the call stack (the fixed-size memory area tracking active function calls) until its children return.Balanced tree (safe): Skewed chain of 100,000 nodes (crashes!): 0 0 -> 1 -> 2 -> ... -> 99,999 / \ 100,000 nested calls -> RecursionError 1 2CPython caps the call stack at roughly
1,000nested calls by default. On a skewed chain of100,000nodes, plain recursion crashes withRecursionError. An iterative loop that stores nodes in standard Python lists avoids the call stack altogether.Subproblem 1: Count tree depth one level at a time
Every child sits one layer below its parent, so the number of nodes on the longest root-to-leaf path equals the total number of non-empty horizontal layers in the tree.
We walk the tree one layer at a time using breadth-first search (BFS) — a traversal that visits all nodes on the current layer before moving to the next layer:
- Guard against
children == []first and return0(otherwise starting at[0]would trychildren[0]and raiseIndexError). - Start with
current_level = [0]anddepth = 0. - While
current_levelis non-empty, add1todepthand collect every valid child (!= -1) intonext_level. Checking!= -1is vital in Python becausechildren[-1]silently reads the last element of the list instead of failing!
def max_tree_depth(children: List[List[int]]) -> int: """Return the maximum node count along any root-to-leaf path (node 0 is root).""" # Phase 1: Handle the empty tree up front so we never index children[0] on []. if not children: return 0 # current_level: list of node IDs on the current depth layer, e.g. [1, 2]. # Non-empty trees are always rooted at node 0. current_level = [0] depth = 0 # Phase 2: Level-by-level breadth-first traversal (no recursion, safe for n = 100,000). # Every non-empty horizontal layer adds 1 to the longest root-to-leaf node count. while current_level: depth += 1 # next_level: collects all existing children of nodes in current_level. next_level = [] for node in current_level: left_child, right_child = children[node] # Check != -1 explicitly: -1 marks "no child", and in Python children[-1] # would silently read the last node instead of raising an error. if left_child != -1: next_level.append(left_child) if right_child != -1: next_level.append(right_child) current_level = next_level return depth- Guard against
Subproblem 2: Why peak overlap equals minimum rooms
Comparing every interval against every other interval takes
O(m^2)time (10^10checks for100,000intervals), and counting pairwise conflicts does not tell us how many freed rooms can be reused later.Instead, ask: what is the maximum number of sessions running at the exact same moment?
- We cannot use fewer rooms than that peak, because simultaneous sessions cannot share a room.
- We never need more rooms than that peak: handing out rooms in start-time order and reusing any freed room only opens a new room when every existing room is currently occupied.
Because the active count only changes when a session starts (
+1) or ends (-1), we use a sweep-line algorithm — converting interval endpoints into sorted events along a timeline and tracking a running counter:Intervals: [2, 12), [4, 8), [6, 11), [9, 14) Time: 2 4 6 8 9 11 12 14 [2, 12): [====================================) [4, 8): [===========) [6, 11): [=================) [9, 14): [=================) Events: +1 +1 +1 -1 +1 -1 -1 -1 Active: 1 2 3 2 3 2 1 0 => peak = 3 roomsSubproblem 2: Tie-breaking at exact boundaries and sweep code
What happens when one session ends at
6and another starts at6, as in Example 2 ([[1, 6], [6, 9], [9, 15]])?Correct order (end before start at t = 6 and t = 9): events: (1, +1) -> (6, -1) -> (6, +1) -> (9, -1) -> (9, +1) -> (15, -1) active: 1 -> 0 -> 1 -> 0 -> 1 -> 0 (peak = 1, right!) Wrong order (start before end at t = 6): events: (1, +1) -> (6, +1) -> (6, -1) -> ... active: 1 -> 2 -> 1 -> ... (peak = 2, wrong!)To vacate a room before reusing it at timestamp
t,(t, -1)must sort before(t, +1). Python compares tuples element by element: when timestamps tie (t == t),-1 < +1places all endings attahead of all starts attautomatically.def min_meeting_rooms(intervals: List[List[int]]) -> int: """Return the minimum conference rooms needed for half-open intervals [start, end).""" # Phase 1: Split each meeting into two timeline events. # events: list of (timestamp, room_delta) tuples, e.g. [(0, 1), (5, 1), (10, -1)]. events = [] for start, end in intervals: events.append((start, 1)) # meeting starts: needs 1 room events.append((end, -1)) # meeting ends: frees 1 room # Phase 2: Sort events chronologically. # Crucial tie-breaker: at the same timestamp t, Python sorts (t, -1) before (t, 1) # because -1 < 1. For half-open intervals [start, end), a meeting ending at t frees # its room before another meeting starting at t claims one. events.sort() # Phase 3: Sweep through the timeline and track the highest simultaneous overlap. active_meetings = 0 max_rooms = 0 for _, room_delta in events: active_meetings += room_delta if active_meetings > max_rooms: max_rooms = active_meetings return max_roomsTrace Example 1 and Example 2 end to end
Example 1: children = [[1, 2], [3, -1], [-1, 4], [-1, 5], [-1, -1], [-1, -1]] Layer 1: current_level = [0] -> depth = 1, next_level = [1, 2] Layer 2: current_level = [1, 2] -> depth = 2, next_level = [3, 4] Layer 3: current_level = [3, 4] -> depth = 3, next_level = [5] Layer 4: current_level = [5] -> depth = 4, next_level = [] Stop -> max_tree_depth = 4 intervals = [[2, 12], [4, 8], [6, 11], [9, 14]] Sorted events: (2,+1), (4,+1), (6,+1), (8,-1), (9,+1), (11,-1), (12,-1), (14,-1) active_meetings: 1 -> 2 -> 3 -> 2 -> 3 -> 2 -> 1 -> 0 max_rooms = 3 Result: [4, 3] Example 2: children = [[-1, 1], [-1, -1]] Layer 1: current_level = [0] -> depth = 1, next_level = [1] Layer 2: current_level = [1] -> depth = 2, next_level = [] Stop -> max_tree_depth = 2 intervals = [[1, 6], [6, 9], [9, 15]] Sorted events: (1,+1), (6,-1), (6,+1), (9,-1), (9,+1), (15,-1) active_meetings: 1 -> 0 -> 1 -> 0 -> 1 -> 0 max_rooms = 1 Result: [2, 1]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def max_tree_depth(children: List[List[int]]) -> int: """Return the maximum node count along any root-to-leaf path (node 0 is root).""" # Phase 1: Handle the empty tree up front so we never index children[0] on []. if not children: return 0 # current_level: list of node IDs on the current depth layer, e.g. [1, 2]. # Non-empty trees are always rooted at node 0. current_level = [0] depth = 0 # Phase 2: Level-by-level breadth-first traversal (no recursion, safe for n = 100,000). # Every non-empty horizontal layer adds 1 to the longest root-to-leaf node count. while current_level: depth += 1 # next_level: collects all existing children of nodes in current_level. next_level = [] for node in current_level: left_child, right_child = children[node] # Check != -1 explicitly: -1 marks "no child", and in Python children[-1] # would silently read the last node instead of raising an error. if left_child != -1: next_level.append(left_child) if right_child != -1: next_level.append(right_child) current_level = next_level return depth def min_meeting_rooms(intervals: List[List[int]]) -> int: """Return the minimum conference rooms needed for half-open intervals [start, end).""" # Phase 1: Split each meeting into two timeline events. # events: list of (timestamp, room_delta) tuples, e.g. [(0, 1), (5, 1), (10, -1)]. events = [] for start, end in intervals: events.append((start, 1)) # meeting starts: needs 1 room events.append((end, -1)) # meeting ends: frees 1 room # Phase 2: Sort events chronologically. # Crucial tie-breaker: at the same timestamp t, Python sorts (t, -1) before (t, 1) # because -1 < 1. For half-open intervals [start, end), a meeting ending at t frees # its room before another meeting starting at t claims one. events.sort() # Phase 3: Sweep through the timeline and track the highest simultaneous overlap. active_meetings = 0 max_rooms = 0 for _, room_delta in events: active_meetings += room_delta if active_meetings > max_rooms: max_rooms = active_meetings return max_rooms def tree_depth_and_meeting_rooms(children: List[List[int]], intervals: List[List[int]]) -> List[int]: # Solve both independent tasks and return [maximum_tree_depth, minimum_rooms]. return [max_tree_depth(children), min_meeting_rooms(intervals)]✅ Submit now — all tests should pass.
Intuition & how it works
Think of the two tasks through two everyday mental models. For binary tree depth, picture the tree as an apartment building where root 0 occupies the top floor, its children sit one floor down, and so on: the longest root-to-leaf node count equals the number of occupied floors, which we count layer by layer using breadth-first search (BFS) — a traversal that visits every node on the current level before advancing to the next level. For room scheduling, picture a venue lobby turnstile that clicks +1 whenever a session begins and -1 whenever a session finishes: the fewest rooms required equals the largest simultaneous crowd inside, which we compute with a sweep-line algorithm — sorting start and end events along a timeline and maintaining a running total. Because each [start, end) is a half-open interval (including start while excluding end), sorting (t, -1) ahead of (t, +1) vacates rooms finishing at time t before new sessions at time t claim a room.
Both naive approaches break down at 100,000 elements. For tree depth, plain recursion (having a function call itself on left and right children) stacks unfinished calls on the call stack — the fixed-size memory region tracking active function calls — which hits CPython's ~1,000-call ceiling and raises RecursionError on a single long chain of nodes. For room scheduling, comparing every session against every other session takes O(m^2) checks (~10 billion comparisons at 100,000 intervals), and stepping tick by tick across integer timestamps is infeasible when coordinates span up to 10^9.
Let's walk through Example 1 (children = [[1, 2], [3, -1], [-1, 4], [-1, 5], [-1, -1], [-1, -1]], intervals = [[2, 12], [4, 8], [6, 11], [9, 14]]):
1. Tree layers: Start at [0] (depth = 1), expand to [1, 2] (depth = 2), expand to [3, 4] (depth = 3), expand to [5] (depth = 4), and finally [] — returning depth 4.
2. Timeline events: Convert the four sessions into (2, +1), (4, +1), (6, +1), (8, -1), (9, +1), (11, -1), (12, -1), (14, -1).
3. Sweep: active_meetings moves through 1 -> 2 -> 3 -> 2 -> 3 -> 2 -> 1 -> 0; its highest value is 3, so the combined output is [4, 3].
Complexity
- Tree depth time —
O(n), wheren = len(children)is the number of tree nodes: every node enterscurrent_levelonce, and we perform oneO(1)lookup (children[node]) plus at most twoO(1)list appends per node. - Tree depth space —
O(w), wherewis the widest tree level (O(n)worst-case): we hold onlycurrent_levelandnext_levelat any time, which is1node on a skewed chain and at most(n + 1) // 2nodes on a complete binary tree (a tree completely filled on every level except possibly the bottom). - Room scheduling time —
O(m log m), wherem = len(intervals)is the number of sessions: building2mtuples takesO(m)time, sorting2mtuples takesO(m log m)time, and the linear sweep inspects each tuple once inO(m)time. - Room scheduling space —
O(m): theeventslist stores2mtwo-element tuples. - Overall:
O(n + m log m)time andO(w + m)auxiliary space.
Edge cases
- Empty tree (
children = []) and empty schedule (intervals = []): Returns[0, 0]cleanly without indexingchildren[0]. - Single node (
[[-1, -1]]) and single session ([[3, 4]]): Returns[1, 1]because depth counts nodes (not edges) and one session needs one room. - 100,000-node skewed chain (all-left, all-right, or zigzag): Runs
100,000loop iterations with1node per level and zero recursion frames. - Back-to-back sessions (
[[1, 6], [6, 9], [9, 15]]):(6, -1)sorts before(6, +1)and(9, -1)sorts before(9, +1), keepingmax_rooms = 1. - Identical sessions (
[[2, 4]] * 5): Five(2, +1)events fire before any(4, -1)event, peaking at5rooms. - Unsorted intervals and negative timestamps: Event sorting relies only on relative numeric order, so negative and out-of-order intervals work identically.
Common mistakes
- Using recursive DFS for tree depth in Python: Passes small balanced trees, then crashes with
RecursionErroron a 100,000-node chain. - Off-by-one depth (counting edges instead of nodes): Returning
0for a single root node instead of1. - Missing the
!= -1child check: In Python,children[-1]is valid syntax that reads the last element ofchildren, causing silent wrong answers or infinite loops! - Sorting start events before end events on ties: Putting
(t, +1)ahead of(t, -1)wrongly charges2rooms for adjacent sessions like[1, 6)and[6, 9). - Counting pairwise overlaps instead of simultaneous overlap: In
[[0, 10], [1, 2], [3, 4]], two pairs overlap, yet[1, 2)and[3, 4)reuse the same second room, so only2rooms are needed.
Alternative approaches
- Iterative depth-first search (DFS) with an explicit stack: Push
(0, 1)((node_id, depth)) onto a Python list, pop in a loop, updatebest_depth, and push valid children withdepth + 1. AlsoO(n)time and recursion-free, usingO(h)stack space for tree heighth. - Min-heap of room end times: A min-heap is a priority queue data structure that retrieves and removes its smallest element in
O(log k)time. Sort intervals bystart; for each session, if the heap's earliest ending room hasearliest_end <= start, pop it (reuse that room), then push the currentend. The final heap size is the room count inO(m log m)time. - Two sorted arrays with two pointers: Sort all
starttimes and allendtimes separately, then advance anend_idxpointer wheneverends[end_idx] <= starts[start_idx]to free a room before allocating one. SameO(m log m)time andO(m)space.
Follow-up questions
- How would you output a concrete room assignment (room index 0 .. k - 1) for every scheduled interval? Tag each interval with its original position
(start, end, original_idx), sort bystart, and maintain a min-heap of(end_time, room_id)for currently busy rooms. When handling(start, end, original_idx), check whether the heap is non-empty and its smallestend_time <= start: if so, pop(end_time, room_id)and reuseroom_id; otherwise allocateroom_id = next_room_idand incrementnext_room_id. Push(end, room_id)back onto the heap and recordassignment[original_idx] = room_idinO(m log m)total time. - What changes if you want the shortest root-to-leaf node count instead of the longest? Keep the same level-by-level BFS loop, and return
depththe instant you visit a node whoseleft_child == -1andright_child == -1(a true leaf). Because BFS explores layers1, 2, 3, ...in increasing order, the very first leaf reached is guaranteed to be closest to the root, letting the search stop early without visiting deeper levels. Be careful not to stop at a node with one child ([-1, 1]), since a node with a child is not a leaf. - How could you maintain the peak room demand dynamically as intervals arrive one at a time? Maintain a dynamic segment tree — a binary tree over coordinate ranges that allocates nodes on demand and supports adding
+1across[start, end - 1]while tracking the range maximum at its root. Each arriving session[start, end)updates[start, end - 1]inO(log U)time (whereUis the timestamp span), and reading the root reports the current global peak inO(1)time.
Follow-up questions
- How would you output a concrete room assignment (room index 0 .. k - 1) for every scheduled interval?
- What changes if you want the shortest root-to-leaf node count instead of the longest?
- How could you maintain the peak room demand dynamically as intervals arrive one at a time?
Similar questions
- Fair Credit Underwriting Risk Classifier
- Diagnosing High Variance from Error Plots
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance