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 unseen customer_id starting at 0 revenue. When referrer_id is not None, referrer_id is guaranteed to refer to an existing customer.
  • add_revenue(customer_id: int, amount: int) -> None: Credits a positive integer amount to customer_id and, when customer_id has a direct referrer, adds the same amount to that referrer's total.
  • get_lowest_revenue_above(threshold: int) -> Optional[int]: Among all registered customers whose cumulative revenue is at least threshold (total_revenue >= threshold), returns the customer_id with the smallest cumulative revenue. Break ties in favor of the smallest customer_id. Return None when no registered customer reaches threshold.

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 registered customer_id is distinct.
  • referrer_id is either None or an already-registered ID in [1, 10^9].
  • 1 <= amount <= 10^6, and customer_id in add_revenue is already registered.
  • 0 <= threshold <= 10^12.
  • Total operations across register_customer, add_revenue, and get_lowest_revenue_above will not exceed 2 * 10^5.
  • Target time complexity is O(log N) per operation, where N is the current count of registered customers.

Step-by-step walkthrough

  1. 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^5 calls, each targeting O(log N) time:

    • register_customer(customer_id, referrer_id): adds a brand-new customer with 0 initial total revenue and an optional already-registered referrer_id.
    • add_revenue(customer_id, amount): adds amount > 0 to customer_id's total revenue and, if customer_id has a direct referrer, adds amount to 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 smallest customer_id (or None if nobody qualifies).
  2. Why a plain dictionary scan is too slow

    If we only store total[customer_id] and referrer[customer_id] in dictionaries, registration and add_revenue take O(1) time, while get_lowest_revenue_above scans 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 best
    

    With 10^5 registered customers and 10^5 threshold queries, scanning all customers per query takes roughly 10^10 steps — far too slow. We need a sorted index so queries avoid scanning everyone.

  3. 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_total to new_total, we remove (old_total, id) and insert (new_total, id). add_revenue updates 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 list or heapq? Inserting or deleting in the middle of a list shifts up to N elements (O(N) time), and a min-heap (heapq) only exposes the global minimum (threshold = 0), not the minimum at or above an arbitrary threshold. Because Python's standard library has no built-in balanced search tree, we write a compact treap.

  4. Build a treap for `O(log N)` insert and remove

    A binary search tree (BST) is a binary tree where every node in node.left has a smaller key than node.key and every node in node.right has a larger key. Plain BSTs can stretch into a slow O(N) chain if keys arrive in sorted order. A treap (tree + heap) fixes this simply: each node also gets a random priority, 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 height O(log N).

    Two short recursive helpers maintain both rules:

    • split(node, key) slices a treap into two valid treaps: smaller (all keys < key) and larger (all keys >= key).
    • merge(left, right) joins two valid treaps when every key in left is already < every key in right, 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 larger
    

    To remove an existing key, remove_key walks down by BST order until node.key == key and replaces that node with merge(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 node
    
  5. Wrap the treap into `SortedPairs` with lower-bound search

    Now we wrap the treap in a clean SortedPairs helper:

    • add(key) splits the tree at key and merges smaller, Node(key), and larger back together.
    • remove(key) calls remove_key.
    • first_with_total_at_least(threshold) walks one root-to-leaf path:
      • If node.key[0] >= threshold, node.key qualifies! Every node in node.right is even larger, so the only place a better (smaller) qualifying tuple can hide is node.left. We save best = node.key and move left.
      • Otherwise (node.key[0] < threshold), node and everything in node.left have revenue below threshold, so we must move right.
    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 best
    
  6. Implement `CustomerRevenueTracker` and the judge driver

    With SortedPairs ready, CustomerRevenueTracker is straightforward. Notice _credit: it always removes (old_total, customer_id) before inserting (new_total, customer_id) so old totals never linger in the index, and add_revenue credits 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 results
    
  7. Trace through Example 1

    Here is how total and by_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               None
    

    The returned list is [None, None, None, None, 10, None, 20, None], matching Example 1.

  8. 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 height O(log N), register_customer does two O(1) dictionary writes plus one O(log N) treap insertion; add_revenue updates at most two customers (two removals and two insertions, each walking one O(log N) root-to-leaf path); and get_lowest_revenue_above walks a single O(log N) root-to-leaf path.
  • Space: O(N) total memory. Each registered customer occupies one entry in self.total, one entry in self.referrer, and exactly one Node in the treap, plus O(log N) expected recursion stack depth during split, merge, and remove_key.

Edge cases

  • Empty tracker or unreachable threshold: When no customer has total_revenue >= threshold, the root-to-leaf walk never sets best and cleanly returns None.
  • threshold = 0: Customers with 0 revenue qualify, and tuple ordering (0, customer_id) automatically selects the smallest customer_id.
  • Exact boundary hit (total_revenue == threshold): Despite "above" in the method name, the specification requires inclusive >=, so a customer with total_revenue == threshold qualifies.
  • Ties on lowest qualifying total: Storing (total_revenue, customer_id) breaks ties by smallest customer_id with zero extra branching.
  • Multi-hop referral chains (100 <- 200 <- 300): Revenue earned by 300 credits 300 and direct referrer 200, never grandparent 100.
  • 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^5 calls of up to 10^6 each, a customer's total can reach 2 * 10^11 (which overflows signed 32-bit integers in C++/Java and requires 64-bit long, though Python int handles arbitrary precision natively), and IDs up to 10^9 are 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 while loop: Only the immediate referrer earns a bonus; indirect ancestors two or more hops up receive nothing.
  • Using strict > instead of >= on threshold: Misreading get_lowest_revenue_above by name rather than by rule fails whenever the best customer equals threshold.
  • Forgetting to re-index the referrer in the treap: Updating self.total[referrer_id] in the dictionary without also moving (old_total, referrer_id) in self.by_revenue makes the index disagree with actual totals.
  • Using bisect.insort on a Python list: Binary search takes O(log N), but shifting list elements on every insert and list.pop(i) takes O(N), timing out on 2 * 10^5 calls.

Alternative approaches

  • Built-in balanced search trees in other languages (or third-party Python): Java's TreeSet.ceiling(new Pair(threshold, 0)) and C++'s std::set::lower_bound({threshold, 0}) use a red-black tree (a self-balancing BST with strict color rules that guarantees O(log N) worst-case height). When third-party libraries are allowed in Python, sortedcontainers.SortedList provides 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 supporting O(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 for d = 1, 2, ..., crediting ancestor curr with the level-d share and updating their treap node at each hop in O(L log N) time for L levels. Cap L (or stop as soon as the integer share drops to 0) so deep chains cannot degrade add_revenue to O(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_revenue updates self.total in O(1) time and adds modified customer IDs to a dirty set without touching the treap, while last_indexed_total[id] remembers what value is currently sitting in the treap. When a rare get_lowest_revenue_above arrives, flush only the dirty set 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 than 1 in N writes, skip the treap altogether and scan self.total in O(N) per query.
  • How can multiple threads record revenue and run threshold queries concurrently without serializing on one coarse lock? Partition customers across S shards (independent slices chosen by customer_id % S, each owning its own lock, total map, and treap). When add_revenue credits 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, while get_lowest_revenue_above queries all S shards and picks the minimum (total, id) in O(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 the O(log N) nodes along a modified path and atomically swaps the root pointer).

Follow-up questions

Similar questions

More Databricks interview questions

All 122 Databricks questions →