← Questions

Peel an N-ary tree one leaf layer per day

0
GoogleCoding

A coding interview question asked at Google. It tests trees, dfs and topological sort.

Every day, all leaves of an N-ary tree fall off at the same time. A leaf is a node with no children left. When a node loses its last child, it becomes a leaf and falls on the next day, not the same day. This repeats until the tree is gone. The root always falls last.

Implement:

class Node:
    val: int
    children: list["Node"]

def leaves_by_day(root: Node | None) -> list[list[int]]: ...

Return days, where days[i] lists the values of the nodes removed on day i + 1. Values inside one day may be in any order. Return [] for an empty tree.

Constraints

  • 0 <= n <= 10^5 nodes. The tree can be very deep (a single chain).
  • Values are integers and may repeat. Treat every node as distinct.
  • You do not need to change the tree. Just report the removal schedule.

Example 1

        10
      /  |  \
    20  30   40
   /  \      |
  50  60     70

Output: [[30, 50, 60, 70], [20, 40], [10]]. On day 1, 30, 50, 60 and 70 are leaves. On day 2, 20 and 40 have no children left. On day 3, only 10 is left.

Example 2

A chain 1 -> 2 -> 3 (each node has one child). Output: [[3], [2], [1]].

Clarifying questions

  • Does a node that becomes a leaf today fall tomorrow, never on the same day (as in example 1)?
  • Is a root with no children removed on day 1?
  • Can the order within each day's list be any order?
  • Should the solution avoid recursion, given a chain of 10^5 nodes?

What a strong answer covers

  • Sees that a node falls on day height + 1, where height is 0 for a leaf and 1 + max(child heights) otherwise, so the schedule is a grouping by height.
  • Computes heights in one post-order traversal, done iteratively for deep chains: O(n) time and space.
  • Groups node values by height without merging nodes that share a value.
  • Mentions the alternative: a BFS from the leaves inward, keeping a count of remaining children per node (this needs parent pointers).
  • Tests an empty tree, a single node, a chain, and a wide star.

Follow-ups

  • Actually detach the nodes from the tree as you go.
  • Return the day on which a given node falls.
  • Do the same for an unrooted tree (peeling leaves until the centre remains).

Where it's asked

What it tests

trees · dfs · topological sort

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding