Aggregate Scores Across a Sponsorship Tree
Data Structure DesignAuto-graded · 13 test casesLast updated
Tests tree traversal and subtree aggregation by computing cumulative scores bottom-up across a forest of sponsor-recruit relationships.
Problem Statement
A competitive gaming platform tracks players and the people who recruited them. Each player has a unique player_id, earns a certain number of points from their own activity, and was recruited by exactly one other player (sponsor_id). Founding players — those who joined without being recruited — have None as their sponsor_id.
A player's cumulative score is their own points plus the cumulative scores of every player they (directly or indirectly) recruited. In other words, it is the total points contributed by their entire recruit subtree, including themselves.
You must implement a class SponsorshipTracker that ingests all player records and answers two types of queries:
class SponsorshipTracker:
def __init__(self, players: list[tuple[int, int, int | None]]):
# players is a list of (player_id, points, sponsor_id)
pass
def get_subtree_revenue(self, player_id: int) -> int:
# Returns the cumulative score for the given player
pass
def find_users_below_threshold(self, threshold: int) -> list[int]:
# Returns a sorted list of player_ids whose cumulative score < threshold
pass
The judge calls a single function with a flat interface (see below). Queries are issued in order; each one uses the state built from the initial player list.
Flat Interface (used by the judge)
track_referral_revenue(players, operations, arguments)
players: a list of[player_id, points, sponsor_id]entries, wheresponsor_idisNonefor founding players.operations: a list of operation names, each either"get_subtree_revenue"or"find_users_below_threshold".arguments: a list of argument lists, one per operation."get_subtree_revenue"receives[player_id]and returns anint."find_users_below_threshold"receives[threshold]and returns a sorted ascendinglist[int]of player IDs.
- Returns a list with one result per operation, in order.
Constraints
- Number of players: up to 10^5.
pointsis a non-negative integer for every player.sponsor_idis eitherNoneor theplayer_idof another player in the list.- The sponsorship structure is guaranteed to be a valid forest (one or more trees with no cycles).
- A player whose cumulative score equals the threshold is not included in
find_users_below_thresholdresults (strict less-than). - Players may appear in the input before their sponsor.
- A
find_users_below_thresholdquery withthreshold = 0always returns[], since points are non-negative.
Examples
Example 1
Input: track_referral_revenue([[1, 10, None], [2, 5, 1], [3, 2, 1], [4, 1, 2]], ['get_subtree_revenue', 'find_users_below_threshold'], [[2], [5]])
Output: [6, [3, 4]]
Hints
Hint 1
Build parent-child relationships in two passes over the input so that a recruit appearing before their sponsor is handled correctly.
Hint 2
A player's cumulative score can only be finalized once every player they recruited has already been finalized — process children before parents using a post-order traversal.
Hint 3
Python's recursion limit will be hit on a sponsorship chain of 100 000 players; replace recursive post-order with an explicit stack, using a boolean flag to distinguish the first visit from the return visit.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight
A player's cumulative score depends on their recruits' cumulative scores, which depend on their recruits, and so on. This dependency flows strictly from leaves toward roots, so one bottom-up (post-order) pass is enough: by the time a node is finalized, every node in its subtree is already finalized.
Step 1 — Build the tree in two passes
Register every player in a points dict and an empty children list during the first pass. In the second pass, attach each player to their sponsor's children list. Two passes are necessary because the input is unordered — a recruit can appear before its sponsor.
Step 2 — Iterative post-order traversal
Seed an explicit stack with every root (any player whose sponsor_id is None). Each stack entry carries a (player_id, visited) flag:
- First pop (visited = False): push the same node back with
visited = True, then push all children withvisited = False. Because the stack is LIFO, every child subtree is fully processed before the parent resurfaces. - Second pop (visited = True): every child's total is already in
totals, sototals[player_id] = points[player_id] + sum(totals[c] for c in children[player_id])is safe.
Using an explicit stack sidesteps Python's recursion limit, which would be exceeded by a sponsorship chain of 100 000 players.
Step 3 — Answer queries
get_subtree_revenue: a single dict lookup — O(1).find_users_below_threshold: scan all totals, collect those strictly below the threshold, and return them sorted by player ID.
Why it is correct
By induction on subtree height:
- Leaves have no recruits, so
total = points. This matches the definition. - Internal nodes: assuming every child's total is correct when finalized, the parent is finalized only after all its children, and its total is its own points plus those correct child totals — exactly the definition of cumulative score.
Because the input is a valid forest, every player is reachable from exactly one root and is finalized exactly once.
Edge cases
- Empty input: no totals are computed; threshold queries return
[]. - Multiple roots: all are seeded onto the stack, so every tree in the forest is covered.
threshold = 0: points are non-negative, so no cumulative score is negative; result is always[].- Score equals threshold: the comparison is strict (
< threshold), so ties are excluded. - Zero-point subtrees: correctly reported below any positive threshold.
- Recruits listed before sponsors: handled by the two-pass build.
Complexity
| Step | Time | Space |
|---|---|---|
| Build maps | O(n) | O(n) |
| Post-order pass | O(n) — each node pushed twice, each edge visited once | O(n) |
get_subtree_revenue | O(1) | O(1) |
find_users_below_threshold | O(n + k log k), k = number of matches | O(k) |
where n is the total number of players.
Reference solution
from typing import List, Optional
def track_referral_revenue(
players: List[List[Optional[int]]],
operations: List[str],
arguments: List[List[int]],
) -> List[Optional[List[int]]]:
points = {}
children = {}
for player_id, pts, sponsor_id in players:
points[player_id] = pts
children[player_id] = []
for player_id, pts, sponsor_id in players:
if sponsor_id is not None:
children[sponsor_id].append(player_id)
totals = {}
stack = [
(player_id, False)
for player_id, _, sponsor_id in players
if sponsor_id is None
]
while stack:
player_id, visited = stack.pop()
if visited:
totals[player_id] = points[player_id] + sum(
totals[child] for child in children[player_id]
)
else:
stack.append((player_id, True))
for child in children[player_id]:
stack.append((child, False))
results = []
for operation, args in zip(operations, arguments):
if operation == "get_subtree_revenue":
results.append(totals[args[0]])
elif operation == "find_users_below_threshold":
threshold = args[0]
results.append(
sorted(
pid for pid, total in totals.items() if total < threshold
)
)
else:
raise ValueError(f"Unknown operation: {operation}")
return results