1657. Same Value Lineage

A family archive stores an N-ary tree: each person (a node) has an integer val giving their trade code and a list of children. A pair of people (a, b) is called an echo when a is a proper ancestor of b (a lies strictly above b on the path from the root) and a and b carry the same trade code. Each echo is counted once, and a node never echoes itself.

Given root, return the number of echoes as a long. Do the work in O(n) time and O(n) space with one traversal: keep a counter table of the codes currently on the path from the root, add a node's code when you enter it, and remove it when you leave. Avoid recursion deeper than necessary, since the tree may be a long chain.

Example 1

Input:
root = [1,null,1,3,null,1,1,null,2]
Output:
5
Explanation:

The root and its first child each hold 1: the root has 3 descendants equal to 1 and that child has 2 (its own two children), giving 5 pairs.

Example 2

Input:
root = [5,null,5,null,5,null,5]
Output:
6
Explanation:

A chain of four equal values 5 has 3 + 2 + 1 = 6 ancestor/descendant pairs.

Constraints

1 ≤ number of nodes ≤ 1000

0 ≤ Node.val ≤ 100

depth of the tree ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…