1650. Bigger Descendants

A company chart has n people numbered 0 to n-1 and n-1 reporting links given in edges as pairs [u, v]; the whole chart is one tree with person 0 at the top. Everyone below a person, at any depth (their reports, the reports of their reports, and so on), counts as that person's descendant. Person i has a salary values[i].

Return an array answer of length n where answer[i] is the number of descendants of person i whose salary is strictly greater than values[i]. Equal salaries do not count, and a person is not their own descendant.

Chains of 50000 people are possible, so traverse iteratively. Aim for O(n log n) time and O(n) space; checking every pair is too slow.

Example 1

Input:
n = 5edges = [[0,1],[0,2],[1,3],[1,4]]values = [4,9,2,5,9]
Output:
[3,0,0,0,0]
Explanation:

Node 0 (value 4) has descendants valued 9, 2, 5 and 9, and three of them are larger; node 1 (value 9) has none larger.

Example 2

Input:
n = 4, edges = [[0,1],[1,2],[2,3]], values = [1,3,3,2]
Output:
[3,0,0,0]
Explanation:

On this chain node 0 has three larger descendants, while node 1 (value 3) sees only an equal 3 and a smaller 2, so it counts none.

Constraints

1 ≤ n ≤ 50000

0 ≤ values[i] ≤ 109

edges has n - 1 pairs [u, v] with 0 ≤ u, v < n and forms a tree rooted at node 0

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 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms

Expected complexity

Time
O(n log 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…