Referral-Aware Customer Revenue Tracker
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Build an in-memory service, CustomerRevenueTracker, that maintains cumulative revenue per customer, applies single-hop referral credits, and answers lower-bound revenue queries efficiently.
Every customer starts with a balance of 0 upon registration and may optionally designate an already-registered customer as their direct referrer. Whenever a customer generates revenue of amount, their own cumulative revenue grows by amount, and if they have a direct referrer, that referrer's cumulative revenue also grows by amount. Referral bonuses stop after one hop — an indirect ancestor (such as the referrer's referrer) receives nothing from the transaction.
Implement CustomerRevenueTracker with these operations:
__init__(): Creates an empty tracker with no registered customers.register_customer(customer_id: int, referrer_id: Optional[int]) -> None: Adds a previously unseencustomer_idstarting at0revenue. Whenreferrer_idis notNone,referrer_idis guaranteed to refer to an existing customer.add_revenue(customer_id: int, amount: int) -> None: Credits a positive integeramounttocustomer_idand, whencustomer_idhas a direct referrer, adds the sameamountto that referrer's total.get_lowest_revenue_above(threshold: int) -> Optional[int]: Among all registered customers whose cumulative revenue is at leastthreshold(total_revenue >= threshold), returns thecustomer_idwith the smallest cumulative revenue. Break ties in favor of the smallestcustomer_id. ReturnNonewhen no registered customer reachesthreshold.
For automated evaluation, customer_revenue_tracker(operations, arguments) instantiates one CustomerRevenueTracker, executes operations[i] with arguments[i] in order, records None for "register_customer" and "add_revenue", and records the returned ID (or None) for "get_lowest_revenue_above".
Examples
Example 1
Input:
operations = [
"register_customer", "register_customer", "register_customer",
"add_revenue", "get_lowest_revenue_above",
"add_revenue", "get_lowest_revenue_above", "get_lowest_revenue_above"
]
arguments = [
[10, None], [20, 10], [15, 10],
[20, 60], [50],
[15, 25], [60], [100]
]
Output:
[None, None, None, None, 10, None, 20, None]
Walk-through:
- Customers 10 (no referrer), 20 (referred by 10), and 15 (referred by 10) all start at 0.
- add_revenue(20, 60) raises customer 20 to 60 and direct referrer 10 to 60 (15 stays at 0).
- get_lowest_revenue_above(50) sees customers 10 (60) and 20 (60) at or above 50; both share the minimum qualifying total 60, so smaller ID 10 wins.
- add_revenue(15, 25) raises customer 15 to 25 and direct referrer 10 from 60 to 85.
- get_lowest_revenue_above(60) includes exact matches (>= 60), comparing customer 20 (60) against customer 10 (85) and returning 20.
- get_lowest_revenue_above(100) returns None because the highest total is 85.
Example 2
Input:
operations = [
"register_customer", "register_customer", "register_customer",
"add_revenue", "get_lowest_revenue_above", "get_lowest_revenue_above"
]
arguments = [
[100, None], [200, 100], [300, 200],
[300, 45], [0], [1]
]
Output:
[None, None, None, None, 100, 200]
Walk-through:
- The referral chain is 100 <- 200 <- 300.
- add_revenue(300, 45) gives 45 to customer 300 and 45 to direct referrer 200, while customer 100 (two hops up) stays at 0.
- get_lowest_revenue_above(0) matches every customer; 100 has the smallest qualifying total (0).
- get_lowest_revenue_above(1) matches 200 (45) and 300 (45), returning smaller ID 200.
Constraints
1 <= customer_id <= 10^9, and every registeredcustomer_idis distinct.referrer_idis eitherNoneor an already-registered ID in[1, 10^9].1 <= amount <= 10^6, andcustomer_idinadd_revenueis already registered.0 <= threshold <= 10^12.- Total operations across
register_customer,add_revenue, andget_lowest_revenue_abovewill not exceed2 * 10^5. - Target time complexity is
O(log N)per operation, whereNis the current count of registered customers.
Step-by-step walkthrough
Understand the problem and rules
Each registered customer has a total revenue equal to their own direct revenue plus the direct revenue earned by anyone they directly referred. Referral credit travels only one level up:
Referral chain: Customer 100 <-- referred -- Customer 200 <-- referred -- Customer 300 When add_revenue(300, 45) runs: Customer 300 gets +45 (earned directly) Customer 200 gets +45 (300's direct referrer) Customer 100 gets +0 (two hops away — no bonus!)We support three methods across up to
2 * 10^5calls, each targetingO(log N)time:register_customer(customer_id, referrer_id): adds a brand-new customer with0initial total revenue and an optional already-registeredreferrer_id.add_revenue(customer_id, amount): addsamount > 0tocustomer_id's total revenue and, ifcustomer_idhas a direct referrer, addsamountto that referrer's total revenue too.get_lowest_revenue_above(threshold): despite"above"in the method name, the rule is greater than or equal to (total >= threshold). Among all qualifying customers, return the one with the smallest total revenue, breaking ties by the smallestcustomer_id(orNoneif nobody qualifies).
Why a plain dictionary scan is too slow
If we only store
total[customer_id]andreferrer[customer_id]in dictionaries, registration andadd_revenuetakeO(1)time, whileget_lowest_revenue_abovescans every customer:def lowest_at_least_scan(total: Dict[int, int], threshold: int) -> Optional[int]: best = None for customer_id, rev in total.items(): if rev >= threshold: if best is None or (rev, customer_id) < (total[best], best): best = customer_id return bestWith
10^5registered customers and10^5threshold queries, scanning all customers per query takes roughly10^10steps — far too slow. We need a sorted index so queries avoid scanning everyone.Key idea: keep `(total_revenue, customer_id)` tuples in an ordered set
In Python, two tuples
(rev_a, id_a)and(rev_b, id_b)compare by the first element first, and by the second element when the first elements tie. That matches our exact ranking rule:Sorted order of (total_revenue, customer_id): (0, 15) < (25, 30) < (60, 10) < (60, 20) < (85, 40) ^ | First pair with total_revenue >= 50 is (60, 10): lowest qualifying total (60), and smallest ID (10 vs 20) on ties!Every customer has one live tuple
(total[id], id)in this ordered set:- When
register_customer(id, ref)runs, we insert(0, id). - When a customer's total increases from
old_totaltonew_total, we remove(old_total, id)and insert(new_total, id).add_revenueupdates at most two customers (the earner and their direct referrer), so it performs at most two removals and two insertions. - Answering
get_lowest_revenue_above(threshold)is a lower-bound search (finding the earliest item in sorted order that satisfies a>=condition).
Why can't we use a sorted Python
listorheapq? Inserting or deleting in the middle of alistshifts up toNelements (O(N)time), and a min-heap (heapq) only exposes the global minimum (threshold = 0), not the minimum at or above an arbitrarythreshold. Because Python's standard library has no built-in balanced search tree, we write a compact treap.- When
Build a treap for `O(log N)` insert and remove
A binary search tree (BST) is a binary tree where every node in
node.lefthas a smaller key thannode.keyand every node innode.righthas a larger key. Plain BSTs can stretch into a slowO(N)chain if keys arrive in sorted order. A treap (tree + heap) fixes this simply: each node also gets a randompriority, and every parent has a priority at least as large as its children's (max-heap rule). Random priorities make the tree behave as if keys were inserted in random order, keeping expected heightO(log N).Two short recursive helpers maintain both rules:
split(node, key)slices a treap into two valid treaps:smaller(all keys< key) andlarger(all keys>= key).merge(left, right)joins two valid treaps when every key inleftis already<every key inright, putting whichever root has the higher priority on top.
split(tree, key): merge(left, right): [node < key] if left.priority > right.priority: / \ [left] L split(R, key) / \ / \ L.left merge(L.right, right) smaller larger -> left result is node (with right=smaller), right result is largerTo remove an existing
key,remove_keywalks down by BST order untilnode.key == keyand replaces that node withmerge(node.left, node.right).class Node: def __init__(self, key: Tuple[int, int]) -> None: # key: (total_revenue, customer_id), e.g. (60, 20) self.key = key # Random heap priority keeps expected tree height O(log N) for any insertion order. self.priority = random.random() self.left: Optional["Node"] = None self.right: Optional["Node"] = None def split(node: Optional[Node], key: Tuple[int, int]) -> Tuple[Optional[Node], Optional[Node]]: """Split a treap into (all nodes with node.key < key, all nodes with node.key >= key).""" if node is None: return None, None if node.key < key: # Root and its entire left subtree are < key, so split inside the right subtree. smaller, larger = split(node.right, key) node.right = smaller return node, larger # Root and its entire right subtree are >= key, so split inside the left subtree. smaller, larger = split(node.left, key) node.left = larger return smaller, node def merge(left: Optional[Node], right: Optional[Node]) -> Optional[Node]: """Join two treaps given that every key in `left` is strictly smaller than every key in `right`.""" if left is None: return right if right is None: return left # Keep whichever root has higher priority on top to preserve the max-heap invariant. if left.priority > right.priority: left.right = merge(left.right, right) return left right.left = merge(left, right.left) return right def remove_key(node: Optional[Node], key: Tuple[int, int]) -> Optional[Node]: """Remove `key` (known to exist in the treap) and return the updated subtree root.""" if node is None: return None if node.key == key: # Splice out this node by merging its left (< key) and right (> key) subtrees. return merge(node.left, node.right) if key < node.key: node.left = remove_key(node.left, key) else: node.right = remove_key(node.right, key) return nodeWrap the treap into `SortedPairs` with lower-bound search
Now we wrap the treap in a clean
SortedPairshelper:add(key)splits the tree atkeyand mergessmaller,Node(key), andlargerback together.remove(key)callsremove_key.first_with_total_at_least(threshold)walks one root-to-leaf path:- If
node.key[0] >= threshold,node.keyqualifies! Every node innode.rightis even larger, so the only place a better (smaller) qualifying tuple can hide isnode.left. We savebest = node.keyand move left. - Otherwise (
node.key[0] < threshold),nodeand everything innode.lefthave revenue belowthreshold, so we must move right.
- If
Searching threshold = 50: (60, 20) 60 >= 50 -> record best=(60, 20), go LEFT / \ (25, 15) (85, 40) 25 < 50 -> too small, go RIGHT \ (60, 10) 60 >= 50 -> record best=(60, 10), go LEFT (None -> stop!) Answer: best = (60, 10)class SortedPairs: """Ordered set of unique (total_revenue, customer_id) pairs backed by a treap.""" def __init__(self) -> None: self.root: Optional[Node] = None def add(self, key: Tuple[int, int]) -> None: smaller, larger = split(self.root, key) self.root = merge(merge(smaller, Node(key)), larger) def remove(self, key: Tuple[int, int]) -> None: self.root = remove_key(self.root, key) def first_with_total_at_least(self, threshold: int) -> Optional[Tuple[int, int]]: """Return the smallest (total_revenue, customer_id) pair with total_revenue >= threshold.""" best: Optional[Tuple[int, int]] = None node = self.root while node is not None: node_revenue = node.key[0] # Inclusive `>=`: a total equal to threshold qualifies. if node_revenue >= threshold: # Current node qualifies; any even smaller qualifying pair (lower revenue, # or equal revenue with smaller customer_id) must lie in the left subtree. best = node.key node = node.left else: # Current node and everything in its left subtree are < threshold; go right. node = node.right return bestImplement `CustomerRevenueTracker` and the judge driver
With
SortedPairsready,CustomerRevenueTrackeris straightforward. Notice_credit: it always removes(old_total, customer_id)before inserting(new_total, customer_id)so old totals never linger in the index, andadd_revenuecredits at most one referrer level.class CustomerRevenueTracker: def __init__(self) -> None: # total: maps customer_id -> current total revenue (direct + 1-level referral), e.g. {10: 85, 20: 60} self.total: Dict[int, int] = {} # referrer: maps customer_id -> direct referrer's customer_id (or None), e.g. {10: None, 20: 10} self.referrer: Dict[int, Optional[int]] = {} # by_revenue: ordered index holding exactly one (total_revenue, customer_id) tuple per customer self.by_revenue = SortedPairs() def register_customer(self, customer_id: int, referrer_id: Optional[int]) -> None: self.total[customer_id] = 0 self.referrer[customer_id] = referrer_id self.by_revenue.add((0, customer_id)) def _credit(self, customer_id: int, amount: int) -> None: # Remove the customer's old tuple before inserting the updated one so stale totals disappear. old_total = self.total[customer_id] new_total = old_total + amount self.by_revenue.remove((old_total, customer_id)) self.total[customer_id] = new_total self.by_revenue.add((new_total, customer_id)) def add_revenue(self, customer_id: int, amount: int) -> None: self._credit(customer_id, amount) # Referral bonus goes strictly one level up to the direct referrer (if any). referrer_id = self.referrer[customer_id] if referrer_id is not None: self._credit(referrer_id, amount) def get_lowest_revenue_above(self, threshold: int) -> Optional[int]: pair = self.by_revenue.first_with_total_at_least(threshold) if pair is None: return None return pair[1] def customer_revenue_tracker(operations: List[str], arguments: List[List[Optional[int]]]) -> List[Optional[int]]: tracker = CustomerRevenueTracker() results: List[Optional[int]] = [] for op, args in zip(operations, arguments): if op == "register_customer": customer_id = int(args[0]) # guaranteed non-None int by problem constraints referrer_id = args[1] tracker.register_customer(customer_id, referrer_id) results.append(None) elif op == "add_revenue": customer_id, amount = int(args[0]), int(args[1]) tracker.add_revenue(customer_id, amount) results.append(None) elif op == "get_lowest_revenue_above": threshold = int(args[0]) results.append(tracker.get_lowest_revenue_above(threshold)) else: raise ValueError(f"unknown operation: {op}") return resultsTrace through Example 1
Here is how
totalandby_revenue(shown in sorted tuple order) evolve across Example 1:Call SortedPairs contents Returned ----------------------------------------------------------------------------- register_customer(10, None) [(0, 10)] None register_customer(20, 10) [(0, 10), (0, 20)] None register_customer(15, 10) [(0, 10), (0, 15), (0, 20)] None add_revenue(20, 60) [(0, 15), (60, 10), (60, 20)] None (20 and referrer 10 get +60) get_lowest_revenue_above(50) first with rev >= 50: (60, 10) 10 (tie at 60 -> smaller ID 10) add_revenue(15, 25) [(25, 15), (60, 20), (85, 10)] None (15 and referrer 10 get +25) get_lowest_revenue_above(60) first with rev >= 60: (60, 20) 20 (inclusive >= 60) get_lowest_revenue_above(100) none with rev >= 100 NoneThe returned list is
[None, None, None, None, 10, None, 20, None], matching Example 1.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import random class Node: def __init__(self, key: Tuple[int, int]) -> None: # key: (total_revenue, customer_id), e.g. (60, 20) self.key = key # Random heap priority keeps expected tree height O(log N) for any insertion order. self.priority = random.random() self.left: Optional["Node"] = None self.right: Optional["Node"] = None def split(node: Optional[Node], key: Tuple[int, int]) -> Tuple[Optional[Node], Optional[Node]]: """Split a treap into (all nodes with node.key < key, all nodes with node.key >= key).""" if node is None: return None, None if node.key < key: # Root and its entire left subtree are < key, so split inside the right subtree. smaller, larger = split(node.right, key) node.right = smaller return node, larger # Root and its entire right subtree are >= key, so split inside the left subtree. smaller, larger = split(node.left, key) node.left = larger return smaller, node def merge(left: Optional[Node], right: Optional[Node]) -> Optional[Node]: """Join two treaps given that every key in `left` is strictly smaller than every key in `right`.""" if left is None: return right if right is None: return left # Keep whichever root has higher priority on top to preserve the max-heap invariant. if left.priority > right.priority: left.right = merge(left.right, right) return left right.left = merge(left, right.left) return right def remove_key(node: Optional[Node], key: Tuple[int, int]) -> Optional[Node]: """Remove `key` (known to exist in the treap) and return the updated subtree root.""" if node is None: return None if node.key == key: # Splice out this node by merging its left (< key) and right (> key) subtrees. return merge(node.left, node.right) if key < node.key: node.left = remove_key(node.left, key) else: node.right = remove_key(node.right, key) return node class SortedPairs: """Ordered set of unique (total_revenue, customer_id) pairs backed by a treap.""" def __init__(self) -> None: self.root: Optional[Node] = None def add(self, key: Tuple[int, int]) -> None: smaller, larger = split(self.root, key) self.root = merge(merge(smaller, Node(key)), larger) def remove(self, key: Tuple[int, int]) -> None: self.root = remove_key(self.root, key) def first_with_total_at_least(self, threshold: int) -> Optional[Tuple[int, int]]: """Return the smallest (total_revenue, customer_id) pair with total_revenue >= threshold.""" best: Optional[Tuple[int, int]] = None node = self.root while node is not None: node_revenue = node.key[0] # Inclusive `>=`: a total equal to threshold qualifies. if node_revenue >= threshold: # Current node qualifies; any even smaller qualifying pair (lower revenue, # or equal revenue with smaller customer_id) must lie in the left subtree. best = node.key node = node.left else: # Current node and everything in its left subtree are < threshold; go right. node = node.right return best class CustomerRevenueTracker: def __init__(self) -> None: # total: maps customer_id -> current total revenue (direct + 1-level referral), e.g. {10: 85, 20: 60} self.total: Dict[int, int] = {} # referrer: maps customer_id -> direct referrer's customer_id (or None), e.g. {10: None, 20: 10} self.referrer: Dict[int, Optional[int]] = {} # by_revenue: ordered index holding exactly one (total_revenue, customer_id) tuple per customer self.by_revenue = SortedPairs() def register_customer(self, customer_id: int, referrer_id: Optional[int]) -> None: self.total[customer_id] = 0 self.referrer[customer_id] = referrer_id self.by_revenue.add((0, customer_id)) def _credit(self, customer_id: int, amount: int) -> None: # Remove the customer's old tuple before inserting the updated one so stale totals disappear. old_total = self.total[customer_id] new_total = old_total + amount self.by_revenue.remove((old_total, customer_id)) self.total[customer_id] = new_total self.by_revenue.add((new_total, customer_id)) def add_revenue(self, customer_id: int, amount: int) -> None: self._credit(customer_id, amount) # Referral bonus goes strictly one level up to the direct referrer (if any). referrer_id = self.referrer[customer_id] if referrer_id is not None: self._credit(referrer_id, amount) def get_lowest_revenue_above(self, threshold: int) -> Optional[int]: pair = self.by_revenue.first_with_total_at_least(threshold) if pair is None: return None return pair[1] def customer_revenue_tracker(operations: List[str], arguments: List[List[Optional[int]]]) -> List[Optional[int]]: tracker = CustomerRevenueTracker() results: List[Optional[int]] = [] for op, args in zip(operations, arguments): if op == "register_customer": customer_id = int(args[0]) # guaranteed non-None int by problem constraints referrer_id = args[1] tracker.register_customer(customer_id, referrer_id) results.append(None) elif op == "add_revenue": customer_id, amount = int(args[0]), int(args[1]) tracker.add_revenue(customer_id, amount) results.append(None) elif op == "get_lowest_revenue_above": threshold = int(args[0]) results.append(tracker.get_lowest_revenue_above(threshold)) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a sales leaderboard rack where every customer has a single index card labeled (total_revenue, customer_id), arranged strictly from lowest revenue on the left to highest revenue on the right (with smaller IDs placed first whenever two totals match). When a customer earns money, we pull out their old card (and their direct referrer's old card, if they have one), add the revenue, and slot the updated card(s) into their new sorted positions. Answering get_lowest_revenue_above(threshold) then becomes a lower-bound search (finding the very first item in sorted order whose value is greater than or equal to a target).
Keeping totals in a plain hash map makes updates O(1), but every threshold query has to scan all N customers in O(N) time, which takes billions of checks across 2 * 10^5 operations. Keeping a sorted Python list makes binary-search queries O(log N), but inserting or removing a card shifts up to N elements in O(N) time, while a min-heap (heapq) only tracks the global minimum rather than a minimum above an arbitrary threshold. To get O(log N) updates and O(log N) threshold queries using only Python's standard library, we store the cards in a treap (a binary search tree that assigns each node a random heap priority so the tree stays balanced automatically).
Walk through a tiny three-customer example:
1. Register 10 (no referrer), 20 (referred by 10), and 15 (referred by 10): sorted index holds (0, 10), (0, 15), (0, 20).
2. add_revenue(20, 60) moves 20 from (0, 20) to (60, 20) and direct referrer 10 from (0, 10) to (60, 10): index is (0, 15), (60, 10), (60, 20).
3. get_lowest_revenue_above(50) walks the treap for the first pair with revenue >= 50, landing on (60, 10) (smallest ID wins the tie at 60) and returning customer 10.
4. add_revenue(15, 25) moves 15 to (25, 15) and referrer 10 to (85, 10): index is (25, 15), (60, 20), (85, 10), so get_lowest_revenue_above(60) lands on (60, 20) and returns customer 20.
Complexity
Let N be the number of registered customers.
- Time:
O(log N)expected per operation. Because random priorities keep the treap's expected heightO(log N),register_customerdoes twoO(1)dictionary writes plus oneO(log N)treap insertion;add_revenueupdates at most two customers (two removals and two insertions, each walking oneO(log N)root-to-leaf path); andget_lowest_revenue_abovewalks a singleO(log N)root-to-leaf path. - Space:
O(N)total memory. Each registered customer occupies one entry inself.total, one entry inself.referrer, and exactly oneNodein the treap, plusO(log N)expected recursion stack depth duringsplit,merge, andremove_key.
Edge cases
- Empty tracker or unreachable threshold: When no customer has
total_revenue >= threshold, the root-to-leaf walk never setsbestand cleanly returnsNone. threshold = 0: Customers with0revenue qualify, and tuple ordering(0, customer_id)automatically selects the smallestcustomer_id.- Exact boundary hit (
total_revenue == threshold): Despite"above"in the method name, the specification requires inclusive>=, so a customer withtotal_revenue == thresholdqualifies. - Ties on lowest qualifying total: Storing
(total_revenue, customer_id)breaks ties by smallestcustomer_idwith zero extra branching. - Multi-hop referral chains (
100 <- 200 <- 300): Revenue earned by300credits300and direct referrer200, never grandparent100. - Single referrer with many referees: A popular referrer accumulates bonuses from every direct referee and moves cleanly in the treap on each update.
- Large revenues and IDs: Across
2 * 10^5calls of up to10^6each, a customer's total can reach2 * 10^11(which overflows signed 32-bit integers in C++/Java and requires 64-bitlong, though Pythoninthandles arbitrary precision natively), and IDs up to10^9are stored in hash maps rather than array indices.
Common mistakes
- Forgetting to remove
(old_total, customer_id)before inserting(new_total, customer_id): Leaving stale pairs in the ordered set makes future queries falsely match a customer's old, lower revenue. - Walking up the entire referral chain in a
whileloop: Only the immediate referrer earns a bonus; indirect ancestors two or more hops up receive nothing. - Using strict
>instead of>=onthreshold: Misreadingget_lowest_revenue_aboveby name rather than by rule fails whenever the best customer equalsthreshold. - Forgetting to re-index the referrer in the treap: Updating
self.total[referrer_id]in the dictionary without also moving(old_total, referrer_id)inself.by_revenuemakes the index disagree with actual totals. - Using
bisect.insorton a Pythonlist: Binary search takesO(log N), but shifting list elements on every insert andlist.pop(i)takesO(N), timing out on2 * 10^5calls.
Alternative approaches
- Built-in balanced search trees in other languages (or third-party Python): Java's
TreeSet.ceiling(new Pair(threshold, 0))and C++'sstd::set::lower_bound({threshold, 0})use a red-black tree (a self-balancing BST with strict color rules that guaranteesO(log N)worst-case height). When third-party libraries are allowed in Python,sortedcontainers.SortedListprovides the same interface using chunked B-tree-like lists. - Offline coordinate compression + Fenwick tree: When the full operation list is known in advance, you can simulate totals once to collect and sort all distinct
(total, id)pairs that ever appear, then maintain active counts in a Fenwick tree (an array-based binary indexed tree supportingO(log M)point updates and prefix sums) with binary lifting. Unlike the treap, however, offline compression cannot handle live interactive calls.
Follow-up questions
- What changes if referral commissions cascade up multiple ancestor levels with a decaying percentage at each hop? Walk up
referrer[curr]in a loop ford = 1, 2, ..., crediting ancestorcurrwith the level-dshare and updating their treap node at each hop inO(L log N)time forLlevels. CapL(or stop as soon as the integer share drops to0) so deep chains cannot degradeadd_revenuetoO(N log N). Store revenues in smallest integer minor units (such as micro-cents) and express fractions in basis points (integer hundredths of a percent, e.g.,500=5.00%) with an explicit integer rounding rule so floating-point drift never corrupts>=comparisons or tie-breaking. - How would you redesign the index when revenue writes vastly outnumber threshold lookups? Switch to lazy indexing:
add_revenueupdatesself.totalinO(1)time and adds modified customer IDs to adirtyset without touching the treap, whilelast_indexed_total[id]remembers what value is currently sitting in the treap. When a rareget_lowest_revenue_abovearrives, flush only thedirtyset into the treap (removing(last_indexed_total[id], id)and inserting(total[id], id)once per dirty customer, even if they had thousands of updates in between), and if queries are rarer than1inNwrites, skip the treap altogether and scanself.totalinO(N)per query. - How can multiple threads record revenue and run threshold queries concurrently without serializing on one coarse lock? Partition customers across
Sshards (independent slices chosen bycustomer_id % S, each owning its own lock,totalmap, and treap). Whenadd_revenuecredits a customer and a referrer in two different shards, acquire the two shard locks in ascending shard-ID order so two threads can never deadlock, whileget_lowest_revenue_abovequeries allSshards and picks the minimum(total, id)inO(S log(N / S))time. If readers require an exact point-in-time snapshot across customers and referrers with zero reader locking, use a persistent treap (an immutable tree that copies only theO(log N)nodes along a modified path and atomically swaps the root pointer).
Follow-up questions
- What changes if referral commissions cascade up multiple ancestor levels with a decaying percentage at each hop?
- How would you redesign the index when revenue writes vastly outnumber threshold lookups?
- How can multiple threads record revenue and run threshold queries concurrently without serializing on one coarse lock?
Similar questions
- Key-Value Store with Sliding-Window Read and Write Rates
- Crash-Safe Key-Value Store with Write-Ahead Log
- Concurrent Cache with Per-Key Read Counts
- Concurrent Key-Value Store with Sliding Read Tallies
- Thread-Safe Asynchronous Event Logger
- Concurrent Write-Ahead Log with Group Commit
More Databricks interview questions
- k-Streak Win Detection on a Rectangular Grid Medium
- First Anagram Substring Index Medium
- Snapshot-Isolated Dynamic Set Hard Pro
- Bounded-Memory Rolling Hit Counter Medium Pro
- Background Intro, Workplace Disagreement, and Flagship Project Medium Pro
- Key-Value Store with Sliding-Window Read and Write Rates Medium Pro
- Behavioral Recruiter Screen Medium Pro
- Trailing Five-Minute In-Memory QPS Tracker Medium Pro
- Bounded-Ply Forced Win Search on Generalized Tic-Tac-Toe Medium Pro
- Enterprise Messaging Core: Sequenced Timelines and Versioned Membership Hard Pro