Taro Logo

Sum of Perfect Square Ancestors

Hard
Asked by:
Meesho
0 views
Topics:
TreesRecursionGraphs

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:

  • In a rooted tree, the ancestors of node 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 = 16
nums[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 = 8
nums[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 <= 105
  • edges.length == n - 1
  • edges[i] = [ui, vi]
  • 0 <= ui, vi <= n - 1
  • nums.length == n
  • 1 <= nums[i] <= 105
  • The input is generated such that edges represents a valid tree.

Solution


Clarifying Questions

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:

  1. Could you explicitly define the "specific mathematical condition involving the node and its ancestor forms a perfect square"? For instance, are we checking absolute difference, product, sum, or something else?
  2. What are the constraints on the node values and the maximum depth/size of the tree?
  3. Can node values be negative, zero, or floating-point numbers, or are they strictly positive integers?
  4. If a node has multiple ancestors that satisfy the perfect square condition, should we sum the values of all valid ancestors for that node, or just the closest one?
  5. What should be returned if the tree is empty or contains only a single root node with no ancestors?

Brute Force Solution

Approach

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:

  1. Begin by picking the first person in the family tree and looking at all of their ancestors who came before them.
  2. For every single ancestor in that family line, take their numerical value and check if it is a perfect square.
  3. Keep a running count of how many of these ancestors meet the perfect square requirement for the person you started with.
  4. Once you finish checking all the ancestors for that first person, write down their final count.
  5. Move on to the next person in the tree and repeat the exact same process of tracing their entire lineage and counting their perfect square ancestors.
  6. Continue this exhaustive checking process for every single member in the entire tree.
  7. Finally, add up all the individual counts you collected for each person to get the grand total for the whole tree.

Code Implementation

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_count

Big(O) Analysis

Time Complexity
O(n²) – For each of the n nodes in the tree, we must traverse its entire lineage to check its ancestors. In the worst-case scenario of a skewed tree, a node can have up to n ancestors to inspect. This means we perform an average of n / 2 ancestor checks for each of the n nodes, resulting in approximately n * n / 2 total operations, which simplifies to O(n²).
Space Complexity
O(N) – To analyze the auxiliary space complexity where N represents the total number of members in the family tree, we must account for the recursion stack and the storage of individual counts. Tracing each person's lineage back to the beginning requires traversing the tree depth-first, which creates recursive call stack frames up to a maximum depth proportional to N in the worst-case scenario of a linear tree. Additionally, storing the running count and final accumulated scores for each of the N members requires auxiliary variables and data structures that scale linearly with the tree size. Consequently, the total extra memory consumed by the algorithm grows proportionally to the input size N, simplifying to Big O notation of O(N).

Optimal Solution

Approach

To 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:

  1. Begin your journey at the very top of the family tree, which represents the root ancestor.
  2. Check if the current person's value is a perfect square, meaning it can be formed by multiplying a whole number by itself.
  3. Keep a running count of how many perfect squares you have encountered along your exact path from the top down.
  4. Before moving to explore a descendant, add the current person's status to your running tally if they are a perfect square.
  5. Visit each child branch recursively, carrying your updated tally with you so every descendant knows their heritage.
  6. Once you finish exploring a branch and are ready to step back up to try a different path, undo the addition you made for the current person so it does not affect unrelated branches.
  7. Combine the results gathered from all the paths to get the final total without ever having to re-examine the same relationship twice.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the total number of nodes in the family tree. We perform a single depth-first traversal of the tree, visiting each node exactly once as we descend and backtrack. At each node, checking if a value is a perfect square takes constant time, O(1), and we update our running tally in constant time as well. Since we visit every node and perform a constant amount of work per node, the total operations approximate 1 * n steps. This simplifies to a final runtime complexity of O(n).
Space Complexity
O(H) – The auxiliary space is primarily driven by the recursion stack used to traverse the family tree from top to bottom. In the worst-case scenario, where the tree forms a straight line or linked list, the recursive calls reach a maximum depth equal to the total number of nodes N. Additionally, checking and updating the running tally of perfect squares uses a constant amount of extra memory per level. Therefore, the total extra memory scales proportionally with the maximum height H of the tree, simplifying to Big O of N in the worst case.

Edge Cases

Null or empty tree root
How to Handle:
Return zero immediately as there are no nodes to process.
Single node tree with no ancestors
How to Handle:
Return zero because a single node has no ancestors to form a relationship with.
Nodes containing negative numbers or zeros
How to Handle:
Ensure the mathematical condition correctly computes absolute values and checks square properties without domain errors.
Extremely large tree leading to deep recursion
How to Handle:
Use iterative DFS with an explicit stack to prevent stack overflow errors on skewed trees.
Large integer values causing multiplication overflow
How to Handle:
Cast node values to 64-bit integers before performing product calculations.
Highly skewed linear tree resembling a linked list
How to Handle:
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
How to Handle:
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
How to Handle:
The running sum remains zero and the function correctly returns zero at the end.