Referral Credit Ledger with Multilevel Propagation
Trees & GraphsAuto-graded · 18 test casesLast updated
Simulate account additions, referral bonus propagation (direct or indirect), and threshold queries ordered deterministically.
Design a system that tracks account balances earned through a referral program.
Accounts are assigned sequential zero-indexed integer IDs (0, 1, 2, ...) as they are created. Upon creation, an account receives an initial credit amount. Additionally, if the new account specifies a valid referrer, credit bonus points are awarded up the referral chain.
You are given a sequence of instructions operations and a boolean flag include_indirect.
Each instruction in operations is represented as a list of strings:
["add", credit, referrer]- Registers a new account with an initial
credit(given as a numeric string). referreris the integer ID string of an existing account, or"-1"if the new account has no referrer.- The newly created account ID is returned as a single-element list of strings
[id_str]. - Credit Propagation Rule: The initial
creditof the new account is awarded to its referrer chain.- If
include_indirectisFalse, only the immediatereferrerreceives the bonus. - If
include_indirectisTrue, the immediatereferrerand all of its ancestors up to the root receive the bonus. - Note: Updating a referrer's balance does not trigger sub-referral events; each
addoperation propagates only the original initialcreditof the new account.
- If
- Registers a new account with an initial
["query", k, threshold]- Queries existing accounts whose total accumulated balance is at least
threshold(parsed as an integer). - Filtered accounts are ordered primarily by
total_creditascending, and secondarily byaccount_idascending. - Returns a list containing the string representation of the IDs of up to the first
kqualifying accounts. If fewer thankaccounts qualify, return all qualifying account IDs. If no accounts qualify, return an empty list[].
- Queries existing accounts whose total accumulated balance is at least
The function must return a list of string lists, where each entry corresponds to the result of the instruction at the same index.
Constraints
- $0 \le \text{len(operations)} \le 2,000$
- $0 \le \text{credit} \le 1,000,000,000$
- $0 \le k \le 2,000$
- $0 \le \text{threshold} \le 2,000,000,000,000$
referreris guaranteed to be a valid existing account ID or"-1".- Accounts are never deleted or re-parented.
Examples
Example 1
Input: track_referrals([['add', '10', '-1'], ['add', '5', '0'], ['add', '7', '1'], ['query', '2', '10']], False)
Output: [['0'], ['1'], ['2'], ['1', '0']]
Example 2
Input: track_referrals([['add', '10', '-1'], ['add', '5', '0'], ['add', '7', '1'], ['query', '2', '20']], True)
Output: [['0'], ['1'], ['2'], ['0']]
Hints
Hint 1
Sequential IDs starting at 0 mean account data can be indexed directly by integer array indices without a hash map.
Hint 2
When propagating bonus credits, pass only the original initial credit of the newly added account—do not propagate the accumulated totals of parents.
Hint 3
Since constraints are modest (up to 2,000 operations), filtering and sorting the accounts on every query operation easily runs within time limits.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to track account balances updated by referral relationships and perform threshold queries.
-
Data Representation: Because account IDs are issued sequentially starting from
0, we can store account balances in a listtotalswheretotals[i]is the balance of accounti. We also maintain a listparentswhereparents[i]is the referrer ID of accounti(or-1). -
Add Operation:
- Parse
creditandreferrer. - The new account ID is
len(totals). Appendcredittototalsandreferrertoparents. - If
referrer != -1, traverse up the referral tree starting fromreferrer. - Add the new account's initial
credit(not the running totals) to each traversed node. - If
include_indirectisFalse, break after updating the directreferrer. Otherwise, continue until reaching-1.
- Parse
-
Query Operation:
- Iterate through all current accounts in
totalsand collect IDs wheretotals[id] >= threshold. - Sort qualifying IDs using the tuple key
(totals[id], id)to enforce ascending credit order and break ties by smaller ID. - Return the string representations of the first
kqualifying IDs.
- Iterate through all current accounts in
Complexity Analysis
-
Time Complexity:
add: $O(1)$ wheninclude_indirectisFalse. Wheninclude_indirectisTrue, traversing up to the root takes $O(d)$ time where $d$ is the depth of the tree ($d \le N$).query: Takes $O(N)$ to filter qualifying accounts and $O(M \log M)$ to sort $M$ qualifying accounts ($M \le N$).- Over $N \le 2,000$ operations, the worst-case overall runtime is $O(N^2 \log N)$, which completes comfortably within a fraction of a second.
-
Space Complexity:
- $O(N)$ space to store
totals,parents, and the generated response structures.
- $O(N)$ space to store
from typing import List
def track_referrals(operations: List[List[str]], include_indirect: bool) -> List[List[str]]:
totals = []
parents = []
result = []
for operation in operations:
if operation[0] == "add":
credit = int(operation[1])
referrer = int(operation[2])
account_id = len(totals)
totals.append(credit)
parents.append(referrer)
if referrer != -1:
current = referrer
while current != -1:
totals[current] += credit
if not include_indirect:
break
current = parents[current]
result.append([str(account_id)])
else:
k = int(operation[1])
threshold = int(operation[2])
qualifying = [
account_id
for account_id, total in enumerate(totals)
if total >= threshold
]
qualifying.sort(key=lambda account_id: (totals[account_id], account_id))
result.append([str(account_id) for account_id in qualifying[:k]])
return result