Ctrl K

First Missing Label in Every Subtree

Hard
You get a tree of n nodes numbered from 0 to n − 1, rooted at node 0. The array parents describes it: parents[i] is the parent of node i, and the root has parents[0] = -1. Each node carries a label, a positive integer labels[i]; all labels are distinct. For every node i, find the smallest positive integer that is not among the labels in its subtree. A node's subtree is the node itself plus all of its descendants. Return an array of these n numbers.
Example 1
parents=[-1, 0, 0, 1], labels=[2, 1, 4, 3] → [5, 2, 1, 1]

The root's subtree holds labels 1, 2, 3, 4, so 5 is the first missing one. Node 1 has labels 1 and 3, so 2 is missing. Nodes 2 and 3 are leaves without label 1, so their answer is 1.

Example 2
parents=[-1, 0, 1], labels=[3, 4, 5] → [1, 1, 1]

No node carries label 1, so 1 is missing from every subtree.

Example 3
parents=[-1, 2, 0, 2], labels=[4, 1, 2, 3] → [5, 2, 4, 1]
Constraints
  • 2 ≤ n ≤ 10⁵, len(parents) = len(labels) = n
  • parents[0] = -1, and 0 ≤ parents[i] < n otherwise; the array describes a valid tree
  • 1 ≤ labels[i] ≤ 10⁵, all labels are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHeaviest Path in a Tree HardDistance Totals in a Road Tree HardFewest Guards on a Tree HardHeaviest Search Subtree HardOther Orders for the Same Search Tree Hard
loading Python…
Input
parents=[-1, 0, 0, 1], labels=[2, 1, 4, 3]
Expected
[5, 2, 1, 1]

Run checks the first 3 tests in your browser. Submit checks all 36 tests on the server, hidden ones included.