KatInterview

Find the Best-Paid Sub-Organization by Mean Pay

Trees & GraphsAuto-graded · 16 test cases
MediumAuto-gradedTrees & Graphstreedfspost-order

Last 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, ...]}. The reports list 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:

  1. Prefer the group with more members.
  2. 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, where N is 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 reports list 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.