KatInterview

Tree Height and Peak Concurrent Bookings

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbinary-treeiterative-dfsintervals

Last updated

Compute the height of an index-encoded binary tree without deep recursion, and the minimum rooms needed for half-open time intervals, returned together as a pair.

Write a single function that answers two independent questions and returns both answers in a list.

Part A: Height of a binary tree

A binary tree is given as an index-based table child_table:

  • child_table[i] = [left, right] holds the indices of the left and right children of node i.
  • A value of -1 means that child does not exist.
  • Node 0 is the root.
  • An empty child_table means the tree is empty.

The height of the tree is the number of nodes on the longest path that starts at the root and ends at a leaf. An empty tree has height 0, and a tree with only a root has height 1.

The tree can contain up to 100,000 nodes and may be extremely lopsided (for example, a single long chain), so your solution should not rely on deep recursion.

Part B: Fewest rooms for a set of bookings

You are given bookings, a list of [start, end) integer pairs. Each booking occupies a room from start (inclusive) up to end (exclusive). Because the ranges are half-open, a booking that ends at time t does not conflict with another booking that starts at time t; they may share a room.

Find the smallest number of rooms such that every booking can be placed in a room with no two overlapping bookings in the same room. If there are no bookings, the answer is 0.

Output

Return a list [height, rooms], where height is the answer to Part A and rooms is the answer to Part B.

Constraints

  • 0 <= len(child_table) <= 100000
  • Each entry of child_table has exactly two integers, each either -1 or a valid node index; the structure is a valid binary tree rooted at node 0.
  • 0 <= len(bookings) <= 100000
  • For every booking, start < end, and both are integers.
  • The two inputs are unrelated to each other.

Examples

Example 1

Input: tree_height_and_min_rooms([[1, 2], [-1, -1], [3, 4], [-1, -1], [-1, -1]], [[0, 30], [5, 10], [15, 20]])

Output: [3, 2]

Example 2

Input: tree_height_and_min_rooms([], [[7, 10], [10, 12]])

Output: [0, 1]

Hints

Hint 1

For the height, each node's level is its parent's level plus one. Track the level alongside each node using an explicit stack (or a queue) rather than recursion.

Hint 2

The rooms needed equal the largest number of bookings active at the same moment. That peak can only increase at a start time.

Hint 3

Sort the start times and the end times separately. As you process each start, first free every booking whose end is less than or equal to that start, then add the new one and track the maximum.