Editor

Team Size and Payroll

#372 · Working with data · Advanced · 130 XP · about 25 min

A company's staff list holds (name, manager, salary) tuples. manager is the name of the person they report to, or None for someone at the top. A person's team is everyone below them: their direct reports, the people who report to those, and so on all the way down.

Write team_rollup(staff) that returns a list of (name, team_size, team_salary) tuples for every person who has at least one report, sorted by name. team_size is the number of people in their team, and team_salary is the total salary of those people (not counting their own).

The rows can come in any order, and a manager may appear after the people who report to them. Every manager named is in the list, and nobody is, directly or through others, their own manager.

Examples

staff = [
    ('Ann', None, 200),
    ('Bob', 'Ann', 120),
    ('Cat', 'Ann', 110),
    ('Dan', 'Bob', 80),
    ('Eve', 'Bob', 75),
    ('Fay', 'Dan', 50),
]
team_rollup(staff)
# returns [('Ann', 5, 435), ('Bob', 3, 205), ('Dan', 1, 50)]

Bob's team is Dan, Eve and Fay (Fay reports to Dan), whose salaries add up to 80 + 75 + 50 = 205.

Constraints

  • 0 <= len(staff) <= 50000, and names are all different.
  • A chain of managers can be tens of thousands of people long, which is far deeper than Python's recursion limit.
  • Salaries are whole numbers from 0 to 1,000,000.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.