Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1.
There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i.
Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i.
The subtree rooted at a node x contains node x and all of its descendant nodes.
Example 1:
Input: parents = [-1,0,0,2], nums = [1,2,3,4] Output: [5,1,1,1] Explanation: The answer for each subtree is calculated as follows: - 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value. - 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value. - 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value. - 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.
Example 2:
Input: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3] Output: [7,1,1,4,2,1] Explanation: The answer for each subtree is calculated as follows: - 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value. - 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value. - 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value. - 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value. - 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value. - 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.
Example 3:
Input: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8] Output: [1,1,1,1,1,1,1] Explanation: The value 1 is missing from all the subtrees.
Constraints:
n == parents.length == nums.length2 <= n <= 1050 <= parents[i] <= n - 1 for i != 0parents[0] == -1parents represents a valid tree.1 <= nums[i] <= 105nums[i] is distinct.Problem summary: There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1. There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i. Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i. The subtree rooted at a node x contains node x and all of its descendant nodes.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Tree · Union-Find
[-1,0,0,2] [1,2,3,4]
[-1,0,1,0,3,3] [5,4,6,2,1,3]
[-1,2,3,0,2,4,1] [2,3,4,5,6,7,8]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2003: Smallest Missing Genetic Value in Each Subtree
class Solution {
private List<Integer>[] g;
private boolean[] vis;
private boolean[] has;
private int[] nums;
public int[] smallestMissingValueSubtree(int[] parents, int[] nums) {
int n = nums.length;
this.nums = nums;
g = new List[n];
vis = new boolean[n];
has = new boolean[n + 2];
Arrays.setAll(g, i -> new ArrayList<>());
int idx = -1;
for (int i = 0; i < n; ++i) {
if (i > 0) {
g[parents[i]].add(i);
}
if (nums[i] == 1) {
idx = i;
}
}
int[] ans = new int[n];
Arrays.fill(ans, 1);
if (idx == -1) {
return ans;
}
for (int i = 2; idx != -1; idx = parents[idx]) {
dfs(idx);
while (has[i]) {
++i;
}
ans[idx] = i;
}
return ans;
}
private void dfs(int i) {
if (vis[i]) {
return;
}
vis[i] = true;
if (nums[i] < has.length) {
has[nums[i]] = true;
}
for (int j : g[i]) {
dfs(j);
}
}
}
// Accepted solution for LeetCode #2003: Smallest Missing Genetic Value in Each Subtree
func smallestMissingValueSubtree(parents []int, nums []int) []int {
n := len(nums)
g := make([][]int, n)
vis := make([]bool, n)
has := make([]bool, n+2)
idx := -1
ans := make([]int, n)
for i, p := range parents {
if i > 0 {
g[p] = append(g[p], i)
}
if nums[i] == 1 {
idx = i
}
ans[i] = 1
}
if idx < 0 {
return ans
}
var dfs func(int)
dfs = func(i int) {
if vis[i] {
return
}
vis[i] = true
if nums[i] < len(has) {
has[nums[i]] = true
}
for _, j := range g[i] {
dfs(j)
}
}
for i := 2; idx != -1; idx = parents[idx] {
dfs(idx)
for has[i] {
i++
}
ans[idx] = i
}
return ans
}
# Accepted solution for LeetCode #2003: Smallest Missing Genetic Value in Each Subtree
class Solution:
def smallestMissingValueSubtree(
self, parents: List[int], nums: List[int]
) -> List[int]:
def dfs(i: int):
if vis[i]:
return
vis[i] = True
if nums[i] < len(has):
has[nums[i]] = True
for j in g[i]:
dfs(j)
n = len(nums)
ans = [1] * n
g = [[] for _ in range(n)]
idx = -1
for i, p in enumerate(parents):
if i:
g[p].append(i)
if nums[i] == 1:
idx = i
if idx == -1:
return ans
vis = [False] * n
has = [False] * (n + 2)
i = 2
while idx != -1:
dfs(idx)
while has[i]:
i += 1
ans[idx] = i
idx = parents[idx]
return ans
// Accepted solution for LeetCode #2003: Smallest Missing Genetic Value in Each Subtree
impl Solution {
pub fn smallest_missing_value_subtree(parents: Vec<i32>, nums: Vec<i32>) -> Vec<i32> {
fn dfs(
i: usize,
vis: &mut Vec<bool>,
has: &mut Vec<bool>,
g: &Vec<Vec<usize>>,
nums: &Vec<i32>,
) {
if vis[i] {
return;
}
vis[i] = true;
if nums[i] < (has.len() as i32) {
has[nums[i] as usize] = true;
}
for &j in &g[i] {
dfs(j, vis, has, g, nums);
}
}
let n = nums.len();
let mut ans = vec![1; n];
let mut g: Vec<Vec<usize>> = vec![vec![]; n];
let mut idx = -1;
for (i, &p) in parents.iter().enumerate() {
if i > 0 {
g[p as usize].push(i);
}
if nums[i] == 1 {
idx = i as i32;
}
}
if idx == -1 {
return ans;
}
let mut vis = vec![false; n];
let mut has = vec![false; (n + 2) as usize];
let mut i = 2;
let mut idx_mut = idx;
while idx_mut != -1 {
dfs(idx_mut as usize, &mut vis, &mut has, &g, &nums);
while has[i] {
i += 1;
}
ans[idx_mut as usize] = i as i32;
idx_mut = parents[idx_mut as usize];
}
ans
}
}
// Accepted solution for LeetCode #2003: Smallest Missing Genetic Value in Each Subtree
function smallestMissingValueSubtree(parents: number[], nums: number[]): number[] {
const n = nums.length;
const g: number[][] = Array.from({ length: n }, () => []);
const vis: boolean[] = Array(n).fill(false);
const has: boolean[] = Array(n + 2).fill(false);
const ans: number[] = Array(n).fill(1);
let idx = -1;
for (let i = 0; i < n; ++i) {
if (i) {
g[parents[i]].push(i);
}
if (nums[i] === 1) {
idx = i;
}
}
if (idx === -1) {
return ans;
}
const dfs = (i: number): void => {
if (vis[i]) {
return;
}
vis[i] = true;
if (nums[i] < has.length) {
has[nums[i]] = true;
}
for (const j of g[i]) {
dfs(j);
}
};
for (let i = 2; ~idx; idx = parents[idx]) {
dfs(idx);
while (has[i]) {
++i;
}
ans[idx] = i;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.