Design a Credit Tracker with Transfers and Top-K Balances

Quick Overview

Design an in-memory credit tracker that creates accounts, adds and spends credits, transfers credits between users, and returns the top k users by balance. It tests hash map design, validation that leaves state unchanged when a call fails, deterministic tie-breaking, and the cost of ranking queries.

Design a Credit Tracker with Transfers and Top-K Balances

Company: Perplexity

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a `CreditTracker` system that manages credit accounts for multiple users. Each user has a unique `userId` and a non-negative integer `balance` of credits. The system supports creating accounts, adding credits, spending credits, transferring credits between users, querying a user's current balance, and retrieving the top `k` users ranked by balance. Spend and transfer operations must fail gracefully (return `False`) when the source user does not have enough credits. Operations referencing a non-existent user should also return `False` or `-1` as appropriate. Implement the following methods: - `createAccount(userId: str, initialBalance: int) -> bool`: Creates a new account with the given initial balance. Returns `False` if the account already exists or `initialBalance` is negative. - `addCredits(userId: str, amount: int) -> bool`: Adds `amount` credits to the user's balance. Returns `False` if the user does not exist or `amount` is negative. - `spendCredits(userId: str, amount: int) -> bool`: Deducts `amount` credits from the user's balance. Returns `False` if the user does not exist or has insufficient balance. - `transfer(fromUserId: str, toUserId: str, amount: int) -> bool`: Transfers `amount` credits from one user to another. Returns `False` if either user is missing or the sender has insufficient balance. - `getBalance(userId: str) -> int`: Returns the current balance for the user, or `-1` if the user does not exist. - `getTopK(k: int) -> List[str]`: Returns up to `k` userIds sorted by balance descending, breaking ties by userId ascending. ```hint Choose the store Every method except `getTopK` reads or writes one or two users by id. Pick a structure that makes those lookups and updates constant time on average. ``` ```hint Order the checks In `transfer`, think about what happens if you debit the sender and only then find out that the receiver does not exist. ``` ### Examples Example 1: ```text Input: ["CreditTracker", "createAccount", "createAccount", "addCredits", "spendCredits", "getBalance", "getBalance", "transfer", "getTopK"] [[], ["alice", 100], ["bob", 50], ["alice", 25], ["bob", 20], ["alice"], ["bob"], ["alice", "bob", 40], [2]] Output: [null, true, true, true, true, 125, 30, true, ["alice", "bob"]] ``` ```python tracker = CreditTracker() # empty tracker tracker.createAccount("alice", 100) # True (alice: 100) tracker.createAccount("bob", 50) # True (bob: 50) tracker.addCredits("alice", 25) # True (alice: 125) tracker.spendCredits("bob", 20) # True (bob: 30) tracker.getBalance("alice") # 125 tracker.getBalance("bob") # 30 tracker.transfer("alice", "bob", 40) # True (alice: 85, bob: 70) tracker.getTopK(2) # ["alice", "bob"] ``` Example 2: ```text Input: ["CreditTracker", "createAccount", "createAccount", "spendCredits", "transfer", "createAccount", "getTopK", "getBalance"] [[], ["u1", 10], ["u1", 5], ["u1", 15], ["u1", "ghost", 5], ["a9", 10], [5], ["ghost"]] Output: [null, true, false, false, false, true, ["a9", "u1"], -1] ``` The second `createAccount("u1", 5)` fails because `u1` already exists, the spend of 15 fails because `u1` holds only 10, and the transfer fails because `ghost` has no account. None of them change a balance, so `u1` and `a9` tie at 10; `"a9"` sorts before `"u1"`, and `getTopK(5)` returns both accounts because only two exist. ### Constraints & Assumptions - `1 <= userId.length <= 20` - `userId` consists of lowercase English letters and digits. - `0 <= initialBalance, amount <= 10^9` - `1 <= k <= 10^4` - At most `10^5` operations will be performed. ### Clarifying Questions to Ask - Should a transfer from a user to themselves succeed, fail, or be treated as a no-op that returns `True`? - Does an amount of 0 count as a successful add, spend or transfer? - How often is `getTopK` called compared with balance updates? - Will several threads call the tracker at the same time? ### What a Strong Answer Covers - The core data structure and the time cost of each method. - The order of validation and mutation in `spendCredits` and `transfer`, and the state left behind by a failed call. - A `getTopK` ordering that stays deterministic when balances tie, and its cost per call. - Edge cases: unknown users, zero amounts, spending the exact balance, self transfers, and `k` larger than the number of accounts. - How the design would change if ranking queries were frequent. ### Follow-up Questions - `getTopK` is now called after almost every balance change and there are `10^5` accounts. How would you change the design, and what does each update cost afterward? - How would you make `transfer` safe when several threads call the tracker at once, including two users transferring to each other at the same moment? - How would you add a transaction history so balances can be audited and a mistaken transfer reversed?

Overview: Design an in-memory credit tracker that creates accounts, adds and spends credits, transfers credits between users, and returns the top k users by balance. It tests hash map design, validation that leaves state unchanged when a call fails, deterministic tie-breaking, and the cost of ranking queries.

Perplexity logo
Perplexity
Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a CreditTracker system that manages credit accounts for multiple users. Each user has a unique userId and a non-negative integer balance of credits.

The system supports creating accounts, adding credits, spending credits, transferring credits between users, querying a user's current balance, and retrieving the top k users ranked by balance.

Spend and transfer operations must fail gracefully (return False) when the source user does not have enough credits. Operations referencing a non-existent user should also return False or -1 as appropriate.

Implement the following methods:

  • createAccount(userId: str, initialBalance: int) -> bool : Creates a new account with the given initial balance. Returns False if the account already exists or initialBalance is negative.
  • addCredits(userId: str, amount: int) -> bool : Adds amount credits to the user's balance. Returns False if the user does not exist or amount is negative.
  • spendCredits(userId: str, amount: int) -> bool : Deducts amount credits from the user's balance. Returns False if the user does not exist or has insufficient balance.
  • transfer(fromUserId: str, toUserId: str, amount: int) -> bool : Transfers amount credits from one user to another. Returns False if either user is missing or the sender has insufficient balance.
  • getBalance(userId: str) -> int : Returns the current balance for the user, or -1 if the user does not exist.
  • getTopK(k: int) -> List[str] : Returns up to k userIds sorted by balance descending, breaking ties by userId ascending.

Examples

Example 1:

Input:
["CreditTracker", "createAccount", "createAccount", "addCredits", "spendCredits", "getBalance", "getBalance", "transfer", "getTopK"]
[[], ["alice", 100], ["bob", 50], ["alice", 25], ["bob", 20], ["alice"], ["bob"], ["alice", "bob", 40], [2]]

Output: [null, true, true, true, true, 125, 30, true, ["alice", "bob"]]
tracker = CreditTracker()                  # empty tracker
tracker.createAccount("alice", 100)        # True   (alice: 100)
tracker.createAccount("bob", 50)           # True   (bob: 50)
tracker.addCredits("alice", 25)            # True   (alice: 125)
tracker.spendCredits("bob", 20)            # True   (bob: 30)
tracker.getBalance("alice")                # 125
tracker.getBalance("bob")                  # 30
tracker.transfer("alice", "bob", 40)       # True   (alice: 85, bob: 70)
tracker.getTopK(2)                         # ["alice", "bob"]

Example 2:

Input:
["CreditTracker", "createAccount", "createAccount", "spendCredits", "transfer", "createAccount", "getTopK", "getBalance"]
[[], ["u1", 10], ["u1", 5], ["u1", 15], ["u1", "ghost", 5], ["a9", 10], [5], ["ghost"]]

Output: [null, true, false, false, false, true, ["a9", "u1"], -1]

The second createAccount("u1", 5) fails because u1 already exists, the spend of 15 fails because u1 holds only 10, and the transfer fails because ghost has no account. None of them change a balance, so u1 and a9 tie at 10; "a9" sorts before "u1", and getTopK(5) returns both accounts because only two exist.

Constraints & Assumptions

  • 1 <= userId.length <= 20
  • userId consists of lowercase English letters and digits.
  • 0 <= initialBalance, amount <= 10^9
  • 1 <= k <= 10^4
  • At most 10^5 operations will be performed.

Clarifying Questions to Ask Guidance

  • Should a transfer from a user to themselves succeed, fail, or be treated as a no-op that returns True ?
  • Does an amount of 0 count as a successful add, spend or transfer?
  • How often is getTopK called compared with balance updates?
  • Will several threads call the tracker at the same time?

What a Strong Answer Covers Guidance

  • The core data structure and the time cost of each method.
  • The order of validation and mutation in spendCredits and transfer , and the state left behind by a failed call.
  • A getTopK ordering that stays deterministic when balances tie, and its cost per call.
  • Edge cases: unknown users, zero amounts, spending the exact balance, self transfers, and k larger than the number of accounts.
  • How the design would change if ranking queries were frequent.

Follow-up Questions Guidance

  • getTopK is now called after almost every balance change and there are 10^5 accounts. How would you change the design, and what does each update cost afterward?
  • How would you make transfer safe when several threads call the tracker at once, including two users transferring to each other at the same moment?
  • How would you add a transaction history so balances can be audited and a mistaken transfer reversed?