#2003
Smallest Missing Genetic Value in Each Subtree
HardArrayDynamic ProgrammingTreeDepth-First SearchUnion-FindHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a depth-first search (DFS) to traverse the tree while maintaining a count of genetic values present in each subtree. This allows us to efficiently determine the smallest missing value without redundant traversals.
⚙️
Algorithm
3 steps- 1Step 1: Build the tree structure from the parents array.
- 2Step 2: Perform a DFS from the root, maintaining a count of genetic values in a boolean array.
- 3Step 3: For each node, find the smallest missing genetic value by checking the boolean array.
solution.py21 lines
1def smallestMissingValue(parents, nums):
2 n = len(parents)
3 ans = [0] * n
4 tree = [[] for _ in range(n)]
5 for i in range(n):
6 if parents[i] != -1:
7 tree[parents[i]].append(i)
8
9 def dfs(node, present):
10 present[nums[node]] = True
11 for child in tree[node]:
12 dfs(child, present)
13
14 for i in range(n):
15 present = [False] * (n + 2)
16 dfs(i, present)
17 for missing in range(1, n + 2):
18 if not present[missing]:
19 ans[i] = missing
20 break
21 return ansℹ
Complexity note: The complexity is O(n) because we traverse each node once and use a boolean array of size n+2 to track present values, allowing us to efficiently find the smallest missing value.
- 1Understanding tree traversal is crucial for solving subtree problems.
- 2Using boolean arrays can help efficiently track presence of values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.