Magicsheet logo

Sum of Perfect Square Ancestors

Hard
12.5%
Updated 8/1/2025

Sum of Perfect Square Ancestors

What is this problem about?

In this advanced tree problem, you are given a tree structure. For each node, you need to identify all of its ancestors whose values are perfect squares. A number is a perfect square if its square root is an integer (e.g., 1, 4, 9, 16...). Your task is to calculate the sum of these perfect square values for all nodes and potentially return the total or an array of results.

Why is this asked in interviews?

This "Hard" problem, seen at Meesho and Amazon, combines tree traversal with number theory. It evaluates a candidate's ability to efficiently track ancestor properties during a DFS. Specifically, it tests whether you can avoid re-calculating the "ancestor sum" for every node by using a "running sum" approach during the traversal.

Algorithmic pattern used

The pattern is "DFS with Running Property Tracking."

  1. Perfect Square Check: Use a helper function or pre-computed set to check if a value is a perfect square.
  2. DFS: Traverse the tree. Maintain a variable current_ancestor_sum that is passed down.
  3. Update: For each node u, if u.val is a perfect square, add it to the current_ancestor_sum before visiting its children.
  4. Result: The "answer" for each node is the sum passed down from its parent.

Example explanation

Tree: 4 (Root) -> 5 (Child) -> 9 (Grandchild)

  • At Root (4): 4 is a perfect square. No ancestors. Sum = 0.
  • At Child (5): Ancestor is 4. 4 is a perfect square. Sum = 4.
  • At Grandchild (9): Ancestors are 4 and 5. Only 4 is a perfect square. Sum = 4. (Note: If the node itself is considered an "ancestor" of its descendants, the Grandchild would have a sum of 4 from its parent, and its own value 9 would be passed to its future children).

Common mistakes candidates make

  1. O(N²) Path Traversal: For every node, walking all the way back up to the root to check ancestors. This is too slow for deep trees.
  2. Inefficient Square Check: Using sqrt() repeatedly. It's better to check int s = sqrt(x); s*s == x.
  3. State Management: Forgetting to subtract the current node's value from the running sum when returning from a recursive call (if using a global variable).

Interview preparation tip

For any problem involving "ancestor properties," try to solve it in a single DFS pass. Think about what information each parent needs to give to its children to satisfy the requirement.

Similar Questions