Subtree Earnings Ledger with Ranked Threshold Queries
Data Structure DesignAuto-graded · 20 test casesLast updated
Simulate a command sequence on a referral forest, maintaining subtree revenue totals and answering ranked queries filtered by a strict threshold.
Subtree Earnings Ledger
You are building an in-memory ledger for customers who may have been brought in by other customers. Each customer earns some revenue of their own, and the ledger must be able to report how much each customer's whole referral subtree has earned.
Concepts
- Own revenue of a customer is the sum of all amounts recorded for that customer directly.
- A customer can have a referrer, another customer who brought them in. This gives a forest: each customer has at most one referrer, and there are no cycles.
- The subtree total of a customer is their own revenue plus the own revenue of every customer that is directly or indirectly referred by them (their children, grandchildren, and so on).
Commands
You are given two parallel lists, commands and payloads. The i-th command is executed with the i-th payload, in order. Every command produces exactly one entry in the returned list.
-
"insert_revenue"with payload[customer_id, amount]or[customer_id, amount, referrer_id]- Add
amountto the own revenue ofcustomer_id. - If
customer_idhas not been seen before, it is created with own revenue 0 before the amount is added. If a referrer is given at that moment, the new customer becomes a child of that referrer. - If the customer already exists, any referrer in the payload is ignored; a customer's position in the forest never changes.
- A referrer given for a new customer is guaranteed to already exist.
- Output entry:
None.
- Add
-
"top_k_above"with payload[k, threshold]- Consider every existing customer whose subtree total is strictly greater than
threshold. - Order them by subtree total from largest to smallest; customers with equal totals are ordered by customer ID ascending.
- Return at most the first
kof them, each as a pair[customer_id, subtree_total]. - Output entry: the list of these pairs (an empty list if none qualify).
- Consider every existing customer whose subtree total is strictly greater than
Task
Implement run_ledger(commands, payloads) that executes all commands in order and returns the list of output entries.
Constraints
len(commands) == len(payloads).- Customer IDs are all of one mutually comparable type (all integers or all strings).
- Amounts and thresholds are numbers;
k >= 0. - No referral cycles exist, and any referrer named for a new customer already exists.
- A query issued before any insert returns
[]. - Aim for a design where each insert only touches the affected customer and its ancestors.
Examples
Example 1
Input: run_ledger(['insert_revenue', 'insert_revenue', 'insert_revenue', 'top_k_above'], [['A', 100], ['B', 50, 'A'], ['C', 75, 'A'], [3, 100]])
Output: [None, None, None, [['A', 225]]]
Example 2
Input: run_ledger(['insert_revenue', 'insert_revenue', 'insert_revenue', 'insert_revenue', 'top_k_above'], [[1, 20], [2, 10, 1], [3, 10, 1], [2, 5], [5, 20]])
Output: [None, None, None, None, [[1, 45]]]
Hints
Hint 1
A new amount changes the subtree total of exactly one customer plus all of that customer's ancestors. No one else is affected.
Hint 2
Store each customer's referrer and keep a running subtree total per customer; on every insert, walk up the referrer chain adding the amount.
Hint 3
For a query, filter totals with a strict greater-than, sort by (negative total, customer ID), and slice the first k. Remember that a referrer is only honored when a customer is first created.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because every customer has at most one referrer, the customers form a forest. When an amount is added to customer C, the subtree total changes for C and for each ancestor of C, and for nobody else.
We keep three dictionaries:
own[c]: the customer's own revenue.referrer_of[c]: the referrer, orNonefor a root.subtree_total[c]: the subtree total, always up to date.
Insert: if the customer is new, initialize its entries and record the referrer (only at creation). Then add the amount to own and walk up the referrer chain, adding the amount to every subtree_total along the way.
Query: collect all customers whose total is strictly greater than the threshold, sort by (-total, customer_id), and return the first k.
Why it is correct
Invariant: after every command, subtree_total[c] equals the sum of own revenue over c's subtree.
- A new customer has no descendants and no revenue, so total 0 is correct.
- Adding
amountto a customer's own revenue increases the subtree sum of exactly the customer and its ancestors, which is precisely the set visited by the upward walk. The walk terminates because there are no cycles. - Links never change after creation, so no totals ever need to be moved between ancestor chains.
The query then reads correct totals and applies the specified filter (strict >) and ordering (total descending, ID ascending), so the output matches the specification. k = 0, k larger than the number of qualifying customers, and no qualifying customers are all handled naturally by slicing.
Complexity
Let n be the number of customers, d the depth of the deepest referral chain, and m the number of customers above the threshold.
- Insert: O(d) time.
- Query: O(n + m log m) time.
- Space: O(n).
Alternatives
- Computing totals lazily at query time makes inserts O(1) but each query needs a full traversal.
- A heap (
heapq.nsmallest) lowers the query sort to O(m log k) whenkis small. - A sorted index keyed by
(-total, id)makes queries fast at the cost of updating every ancestor's entry on insert.
Reference solution
from typing import List
def run_ledger(commands: List[str], payloads: List[List]) -> List[List]:
own = {}
referrer_of = {}
subtree_total = {}
outputs = []
for command, payload in zip(commands, payloads):
if command == "insert_revenue":
customer_id, amount, *extra = payload
referrer_id = extra[0] if extra else None
if customer_id not in own:
own[customer_id] = 0
subtree_total[customer_id] = 0
referrer_of[customer_id] = referrer_id
own[customer_id] += amount
node = customer_id
while node is not None:
subtree_total[node] += amount
node = referrer_of[node]
outputs.append(None)
elif command == "top_k_above":
k, threshold = payload
qualifying = [
[cid, total]
for cid, total in subtree_total.items()
if total > threshold
]
qualifying.sort(key=lambda pair: (-pair[1], pair[0]))
outputs.append(qualifying[:k])
else:
raise ValueError("unknown command")
return outputs