Find the Best-Paid Sub-Organization by Mean Pay
Trees & GraphsAuto-graded · 16 test casesLast updated
Aggregate subtree salary totals and headcounts bottom-up in a tree given as a flat list, then pick the best root using exact average comparison with size and id tie-breaks.
Best-Paid Sub-Organization
A company's reporting structure forms a rooted tree. The root is the top executive. Every person has a unique integer id, a non-negative salary, and a list of the ids of the people who report directly to them.
For any person p, the group of p is p together with everyone who reports to p directly or indirectly. This is the whole subtree rooted at p. The mean pay of a group is the total salary of its members divided by the number of members.
Return the id of the person whose group has the greatest mean pay.
Input
staff: a list of dictionaries, one per person, each of the form{"id": int, "salary": number, "reports": [int, ...]}. Thereportslist holds the ids of direct reports, not objects.top_id: the id of the root of the tree.
Output
An integer: the id of the person whose group wins.
Tie-breaking
If several groups have exactly the same mean pay:
- Prefer the group with more members.
- If still tied, prefer the smaller
id.
Means must be compared exactly. Two groups whose true means are equal must be treated as tied, even if a naive floating-point division would give slightly different values.
Constraints
1 <= N <= 50,000, whereNis the number of people.0 <= salary <= 10^7(integer or floating-point).1 <= id <= 10^9, and all ids are unique.- The input describes a valid tree: a single root, no cycles, and every person appears in exactly one
reportslist except the root. - The hierarchy may be a long chain, so deep nesting must be handled safely.
Examples
Example 1
Input: best_paid_group_leader([{'id': 1, 'salary': 100, 'reports': [2, 3]}, {'id': 2, 'salary': 120, 'reports': [4]}, {'id': 3, 'salary': 80, 'reports': []}, {'id': 4, 'salary': 150, 'reports': []}], 1)
Output: 4
Example 2
Input: best_paid_group_leader([{'id': 10, 'salary': 90, 'reports': [20, 30]}, {'id': 20, 'salary': 90, 'reports': []}, {'id': 30, 'salary': 90, 'reports': []}], 10)
Output: 10
Hints
Hint 1
A group's total salary and member count can be built from its direct reports' totals and counts, so process people children-first.
Hint 2
With up to 50,000 people in a possible chain, avoid recursion. Record a pre-order using an explicit stack, then walk that order in reverse so children are handled before parents.
Hint 3
Avoid dividing. Compare a/b versus c/d as a*d versus c*b, and keep salary sums exact (for example with Fraction) so equal means really compare equal before applying the size and id tie-breaks.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A group's mean is group_sum / group_size. Both values come from the children:
group_sum(p) = salary(p) + sum of group_sum(child)group_size(p) = 1 + sum of group_size(child)
So we need a bottom-up (post-order) pass. To stay safe on chains of 50,000 people, we avoid recursion:
- Build an
id -> personmap. - Do an iterative pre-order traversal from
top_idwith an explicit stack, recording the visit order. In pre-order every parent appears before all of its descendants. - Process that order in reverse. Every person is then handled after all of their descendants, so the children's
(sum, size)pairs are already stored. - For each person, compute
(sum, size)and compare it with the current best.
Exact comparison
Salaries are converted to exact rationals with Fraction.from_float, so sums have no rounding error. Two means s1/n1 and s2/n2 are compared by cross-multiplying (s1*n2 versus s2*n1), which is valid because sizes are positive. Equal means are therefore detected exactly, and the tie-breaks apply correctly.
A candidate replaces the current best when its mean is strictly higher, or the means are equal and its size is larger, or the means and sizes are equal and its id is smaller. This is a strict total order (ids are unique), so the result does not depend on visiting order.
Why it is correct
- Every person is reached exactly once because the input is a tree.
- By induction from the leaves upward, each stored pair is the true sum and size of that person's group.
- Each person is compared under an order that matches the problem's rules, so the survivor is the maximum under that order.
Complexity
- Time: O(N) node and edge operations (Fraction arithmetic adds a small constant factor, since denominators are powers of two).
- Space: O(N) for the map, the order, the stack and the totals.
Reference solution
from fractions import Fraction
from typing import Dict, List
def best_paid_group_leader(staff: List[Dict], top_id: int) -> int:
people = {p["id"]: p for p in staff}
# Iterative pre-order; reversed, it visits children before parents.
order = []
stack = [top_id]
while stack:
cur = stack.pop()
order.append(cur)
stack.extend(people[cur]["reports"])
totals = {} # id -> (exact salary sum, member count)
best_id = None
best_size = 0
for pid in reversed(order):
person = people[pid]
total = Fraction.from_float(float(person["salary"]))
size = 1
for child in person["reports"]:
c_sum, c_size = totals[child]
total += c_sum
size += c_size
totals[pid] = (total, size)
if best_id is None:
better = True
else:
best_total, best_team_size = totals[best_id]
left = total * best_team_size
right = best_total * size
better = (
left > right
or (
left == right
and (size > best_size or (size == best_size and pid < best_id))
)
)
if better:
best_id = pid
best_size = size
return best_id