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]:

  1. Binary tree node depth (children):

    • When children is empty ([]), the tree contains no nodes and max_depth is 0.
    • When children has length n > 0, the tree contains n nodes numbered 0 through n - 1, with node 0 as the root. Entry children[i] = [left, right] lists the left and right child indices of node i, using -1 when no child exists on that side.
    • max_depth is the largest count of nodes along any downward path from root 0 to a leaf node ([-1, -1]). Trees may be severely skewed (such as a single chain of 100,000 nodes), so your traversal must avoid overflowing the call stack.
  2. Peak room allocation (intervals):

    • Each element [start, end] in intervals represents a session spanning the half-open integer window [start, end), meaning it occupies times t with start <= t < end.
    • No two overlapping sessions may occupy the same room. Because the upper bound end is exclusive, a session ending at timestamp t frees its room just in time for a session starting at t to use the same room.
    • min_rooms is the smallest number of rooms needed to accommodate every session (0 if intervals is empty).

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, node 0 is the root, each children[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

  1. Understand both tasks and input shapes

    This function solves two independent problems and returns [depth, rooms]:

    1. Binary tree node depth (children):
      • Nodes are numbered 0 through n - 1, with node 0 as the root (the top node) whenever the tree is non-empty. An empty list [] represents an empty tree (depth 0).
      • children[i] = [left_child, right_child] stores the indices of node i's two children, using -1 to 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).
    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
    
    1. Minimum rooms (intervals):
      • Each interval [start, end] represents a half-open interval [start, end) — it occupies times t where start <= t < end.
      • Because end is excluded, a session [1, 6) vacates its room right at timestamp 6, so [6, 9) can reuse that exact same room (1 room total).

    Both inputs can have up to 100,000 items, which rules out O(n^2) scans and deep recursion in Python.

  2. Subproblem 1: Why plain recursion fails on skewed trees

    The textbook formula for tree depth is 1 + max(depth(left), depth(right)), returning 0 when 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     2
    

    CPython caps the call stack at roughly 1,000 nested calls by default. On a skewed chain of 100,000 nodes, plain recursion crashes with RecursionError. An iterative loop that stores nodes in standard Python lists avoids the call stack altogether.

  3. 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:

    1. Guard against children == [] first and return 0 (otherwise starting at [0] would try children[0] and raise IndexError).
    2. Start with current_level = [0] and depth = 0.
    3. While current_level is non-empty, add 1 to depth and collect every valid child (!= -1) into next_level. Checking != -1 is vital in Python because children[-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
    
  4. Subproblem 2: Why peak overlap equals minimum rooms

    Comparing every interval against every other interval takes O(m^2) time (10^10 checks for 100,000 intervals), 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 rooms
    
  5. Subproblem 2: Tie-breaking at exact boundaries and sweep code

    What happens when one session ends at 6 and another starts at 6, 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 < +1 places all endings at t ahead of all starts at t automatically.

    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
    
  6. Trace 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]
    
  7. 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), where n = len(children) is the number of tree nodes: every node enters current_level once, and we perform one O(1) lookup (children[node]) plus at most two O(1) list appends per node.
  • Tree depth space — O(w), where w is the widest tree level (O(n) worst-case): we hold only current_level and next_level at any time, which is 1 node on a skewed chain and at most (n + 1) // 2 nodes on a complete binary tree (a tree completely filled on every level except possibly the bottom).
  • Room scheduling time — O(m log m), where m = len(intervals) is the number of sessions: building 2m tuples takes O(m) time, sorting 2m tuples takes O(m log m) time, and the linear sweep inspects each tuple once in O(m) time.
  • Room scheduling space — O(m): the events list stores 2m two-element tuples.
  • Overall: O(n + m log m) time and O(w + m) auxiliary space.

Edge cases

  • Empty tree (children = []) and empty schedule (intervals = []): Returns [0, 0] cleanly without indexing children[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,000 loop iterations with 1 node 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), keeping max_rooms = 1.
  • Identical sessions ([[2, 4]] * 5): Five (2, +1) events fire before any (4, -1) event, peaking at 5 rooms.
  • 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 RecursionError on a 100,000-node chain.
  • Off-by-one depth (counting edges instead of nodes): Returning 0 for a single root node instead of 1.
  • Missing the != -1 child check: In Python, children[-1] is valid syntax that reads the last element of children, causing silent wrong answers or infinite loops!
  • Sorting start events before end events on ties: Putting (t, +1) ahead of (t, -1) wrongly charges 2 rooms 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 only 2 rooms 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, update best_depth, and push valid children with depth + 1. Also O(n) time and recursion-free, using O(h) stack space for tree height h.
  • 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 by start; for each session, if the heap's earliest ending room has earliest_end <= start, pop it (reuse that room), then push the current end. The final heap size is the room count in O(m log m) time.
  • Two sorted arrays with two pointers: Sort all start times and all end times separately, then advance an end_idx pointer whenever ends[end_idx] <= starts[start_idx] to free a room before allocating one. Same O(m log m) time and O(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 by start, 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 smallest end_time <= start: if so, pop (end_time, room_id) and reuse room_id; otherwise allocate room_id = next_room_id and increment next_room_id. Push (end, room_id) back onto the heap and record assignment[original_idx] = room_id in O(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 depth the instant you visit a node whose left_child == -1 and right_child == -1 (a true leaf). Because BFS explores layers 1, 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 +1 across [start, end - 1] while tracking the range maximum at its root. Each arriving session [start, end) updates [start, end - 1] in O(log U) time (where U is the timestamp span), and reading the root reports the current global peak in O(1) time.

Follow-up questions

Similar questions

More Zest AI interview questions

All 3 Zest AI questions →