You are given an integer n and an undirected tree rooted at node 0 with n nodes numbered from 0 to n - 1. This is represented by a 2D array edges of length n - 1, where edges[i] = [ui, vi] indicates an undirected edge between nodes ui and vi.
You are also given an integer array nums, where nums[i] is the positive integer assigned to node i.
Define a value ti as the number of ancestors of node i such that the product nums[i] * nums[ancestor] is a perfect square.
Return the sum of all ti values for all nodes i in range [1, n - 1].
Note:
i are all nodes on the path from node i to the root node 0, excluding i itself.Example 1:
Input: n = 3, edges = [[0,1],[1,2]], nums = [2,8,2]
Output: 3
Explanation:
i |
Ancestors | nums[i] * nums[ancestor] |
Square Check | ti |
|---|---|---|---|---|
| 1 | [0] | nums[1] * nums[0] = 8 * 2 = 16 |
16 is a perfect square | 1 |
| 2 | [1, 0] | nums[2] * nums[1] = 2 * 8 = 16nums[2] * nums[0] = 2 * 2 = 4 |
Both 4 and 16 are perfect squares | 2 |
Thus, the total number of valid ancestor pairs across all non-root nodes is 1 + 2 = 3.
Example 2:
Input: n = 3, edges = [[0,1],[0,2]], nums = [1,2,4]
Output: 1
Explanation:
i |
Ancestors | nums[i] * nums[ancestor] |
Square Check | ti |
|---|---|---|---|---|
| 1 | [0] | nums[1] * nums[0] = 2 * 1 = 2 |
2 is not a perfect square | 0 |
| 2 | [0] | nums[2] * nums[0] = 4 * 1 = 4 |
4 is a perfect square | 1 |
Thus, the total number of valid ancestor pairs across all non-root nodes is 1.
Example 3:
Input: n = 4, edges = [[0,1],[0,2],[1,3]], nums = [1,2,9,4]
Output: 2
Explanation:
i |
Ancestors | nums[i] * nums[ancestor] |
Square Check | ti |
|---|---|---|---|---|
| 1 | [0] | nums[1] * nums[0] = 2 * 1 = 2 |
2 is not a perfect square | 0 |
| 2 | [0] | nums[2] * nums[0] = 9 * 1 = 9 |
9 is a perfect square | 1 |
| 3 | [1, 0] | nums[3] * nums[1] = 4 * 2 = 8nums[3] * nums[0] = 4 * 1 = 4 |
Only 4 is a perfect square | 1 |
Thus, the total number of valid ancestor pairs across all non-root nodes is 0 + 1 + 1 = 2.
Constraints:
1 <= n <= 105edges.length == n - 1edges[i] = [ui, vi]0 <= ui, vi <= n - 1nums.length == n1 <= nums[i] <= 105edges represents a valid tree.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To solve this problem using the brute force approach, we want to look at every single relationship in the family tree of numbers from top to bottom. For each number, we will trace its entire lineage back to the very beginning and check if any of those ancestral values are special numbers that can be multiplied by themselves to make a whole number.
Here's how the algorithm would work step-by-step:
import math
def sum_of_perfect_square_ancestors(tree_nodes, parent_mapping):
total_square_count = 0
# Iterate through every node in the tree to independently evaluate its entire ancestral lineage
for current_node in tree_nodes:
ancestor_pointer = parent_mapping.get(current_node)
while ancestor_pointer is not None:
square_root = int(math.isqrt(ancestor_pointer))
# Verify if the current ancestor is a valid perfect square before incrementing our running total
if square_root * square_root == ancestor_pointer:
total_square_count += 1
ancestor_pointer = parent_mapping.get(ancestor_pointer)
# Aggregate all individual ancestral findings into a final sum representing the entire tree structure
return total_square_countTo efficiently find how many ancestors have values that are perfect squares, we can explore the family tree from top to bottom while keeping a running tally of these special numbers. Instead of recalculating or looking backward for every single person, we carry our findings down the path and simply undo our additions when we step back up.
Here's how the algorithm would work step-by-step:
import math
def sum_perfect_square_ancestors(root_node):
def is_perfect_square(node_value):
if node_value < 0:
return False
root_integer = int(math.isqrt(node_value))
return root_integer * root_integer == node_value
def traverse_tree(current_node, square_ancestor_count):
if current_node is None:
return 0
current_node_is_square = is_perfect_square(current_node.val)
# We add to the running tally before exploring descendants to pass down the correct heritage.
updated_square_count = square_ancestor_count + (1 if current_node_is_square else 0)
accumulated_total_squares = square_ancestor_count
for child_node in current_node.children:
accumulated_total_squares += traverse_tree(child_node, updated_square_count)
# Backtracking by default when returning implicitly undoes the tally update for sibling branches.
return accumulated_total_squares
# We initiate the recursive journey from the root node with an initial square ancestor tally of zero.
return traverse_tree(root_node, 0)| Case | How to Handle |
|---|---|
| Null or empty tree root | Return zero immediately as there are no nodes to process. |
| Single node tree with no ancestors | Return zero because a single node has no ancestors to form a relationship with. |
| Nodes containing negative numbers or zeros | Ensure the mathematical condition correctly computes absolute values and checks square properties without domain errors. |
| Extremely large tree leading to deep recursion | Use iterative DFS with an explicit stack to prevent stack overflow errors on skewed trees. |
| Large integer values causing multiplication overflow | Cast node values to 64-bit integers before performing product calculations. |
| Highly skewed linear tree resembling a linked list | Maintain the current path of ancestors efficiently using a dynamic list or stack during traversal. |
| Values that form perfect squares via absolute difference or product | Implement a helper function that accurately verifies if a number is an integer square using integer square root checks. |
| No ancestor pairs satisfy the perfect square condition | The running sum remains zero and the function correctly returns zero at the end. |