Databricks questions

Referral Credit Tracker

DatabricksOnsiteMedium

Each test creates one ReferralTracker and then runs a sequence of calls, checking every return value. Accounts get integer ids in the order they are added: the first account is 0, the next is 1, and so on.

Part 1: Track referral credit

Build a referral credit tracker for accounts.

Implement the class ReferralTracker:

  • The constructor takes indirect, a bool that picks how credit spreads.
  • add(credit, referrer) creates the next account with a starting total of credit and returns its id. referrer is the id of an existing account, or -1 when nobody referred this account. The referrer's total grows by credit right away. When indirect is False, only that referrer is credited. When indirect is True, the credit goes to every account on the referral chain: the referrer, its referrer, and so on up to an account nobody referred. Each of them receives one copy of the new account's starting credit, not a copy of any current total.
  • query(k, threshold) returns the ids of all accounts whose current total is at least threshold, ordered by total from smallest to largest, with equal totals ordered by smaller id first, cut to the first k ids of that order. It returns an empty list when no account qualifies or when k is 0.
  1. Example 1
    init
    [false]
    operations
    [["add",[10,-1]],["add",[5,0]],["add",[7,1]],["query",[2,10]],["query",[10,0]],["query",[3,100]],["query",[0,0]]]
    Output
    [0,1,2,[1,0],[2,1,0],[],[]]

    Why: In direct mode each credit goes only to the account that referred the new one. Totals: account 0 has 10 + 5 = 15, account 1 has 5 + 7 = 12, account 2 has 7. Sorted by total the order is 2, 1, 0, so query(2, 10) keeps 1 and 0; a threshold of 0 keeps all three, a threshold of 100 keeps none, and k = 0 returns an empty list.

  2. Example 2
    init
    [true]
    operations
    [["add",[10,-1]],["add",[5,0]],["add",[7,1]],["query",[2,20]],["query",[3,10]]]
    Output
    [0,1,2,[0],[1,0]]

    Why: In indirect mode account 2's credit of 7 goes to its referrer 1 and to 1's referrer 0. Totals: account 0 has 10 + 5 + 7 = 22, account 1 has 5 + 7 = 12, account 2 has 7. Only account 0 reaches 20; a threshold of 10 keeps 1 and 0 in total order.

Constraints

  • 0 <= credit <= 10^9
  • referrer is -1 or the id of an account that already exists
  • 0 <= k <= 2000
  • 0 <= threshold <= 2 * 10^12
  • 1 <= len(operations) <= 2000
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question