KatInterview

Escrow-Style Ledger with Expiring Transfers and Account Merging

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designsimulationhash-mapheap

Last updated

Simulate an in-memory ledger with held transfers that expire after a day, account merging, and a ranking of accounts by completed outgoing totals.

You are building a small in-memory ledger and replaying a batch of commands against it. Implement run_bank_ledger(commands, params). It takes two parallel lists, where commands[i] is the name of an operation and params[i] is the list of its arguments. It applies the operations in order, starting from an empty ledger, and returns a list with one result per operation.

Timestamps are integers in milliseconds and are non-decreasing across the batch. Account ids are strings. Amounts are non-negative integers.

Transfers and expiration

A transfer moves money in two steps. When it is created, the money is taken out of the source balance and held. It stays pending until the target accepts it. A transfer created at time t expires once the clock reaches t + 86_400_000. At any timestamp greater than or equal to t + 86_400_000, a still-pending transfer is expired. When a transfer expires, its held amount goes back to the balance of its current source account.

Every operation except create_account must first expire all pending transfers whose deadline has been reached at that operation's timestamp, and only then do its own work.

Operations

Each params[i] has the argument layout shown below, and the result is appended to the output list. null means None.

  1. create_account with [timestamp, account_id]

    • If the id is new, create the account with balance 0 and outgoing total 0, and return true.
    • If the id already exists, change nothing and return false.
  2. deposit with [timestamp, account_id, amount]

    • Add amount to the account and return the new balance.
    • Return null if the account does not exist.
  3. transfer with [timestamp, source_id, target_id, amount]

    • Return null if either account does not exist, if the two ids are equal, or if the source balance is less than amount.
    • Otherwise subtract amount from the source balance immediately, record a pending transfer, and return its id as a string. Ids are "transfer1", "transfer2", and so on. The counter advances only when a transfer is successfully created.
  4. accept_transfer with [timestamp, account_id, transfer_id]

    • Return true only if the transfer exists, is still pending, and account_id is its current target. In that case, add the held amount to the target's balance, add it to the source's outgoing total, and mark the transfer accepted.
    • Otherwise return false. This covers unknown ids, transfers already accepted, expired, or canceled, and the wrong account.
  5. top_outgoing with [timestamp, n]

    • Rank all existing accounts by outgoing total, largest first. Ties are broken by the lexicographically smaller account id.
    • Return the ids of the first n accounts as a list of strings. If n is larger than the number of accounts, return all of them. If n is 0 or negative, return an empty list.
    • Only accepted transfers count toward outgoing totals. Pending and expired transfers do not. Accounts with outgoing total 0 are still ranked.
  6. merge_accounts with [timestamp, destination_id, source_id]

    • Return false and change nothing if either account does not exist or the two ids are equal.
    • Otherwise:
      • Add the source's balance and outgoing total to the destination's.
      • Every pending transfer that goes between the destination and the source, in either direction, is canceled, and its held amount is added to the destination's balance.
      • Every other pending transfer whose source or target is the source account is rewritten to use the destination account instead. Its held money stays held, and its original deadline is unchanged.
      • Delete the source account.
    • Return true.

An unknown command name is invalid input and may raise ValueError.

Output

Return a list of results in the same order as the commands. Results are booleans, integers, strings, lists of strings, or None, as described above.

Constraints

  • len(commands) == len(params).
  • Timestamps are non-negative integers and never decrease from one operation to the next.
  • Amounts are non-negative integers. Zero-amount deposits and transfers are valid.
  • Account ids are non-empty strings. Comparison for tie-breaking is standard string ordering.
  • Canceled, accepted, and expired transfers can never be accepted later.
  • The number of operations is small enough for a straightforward simulation. A scan over all transfers during merge_accounts is acceptable.

Examples

Example 1

Input: run_bank_ledger(['create_account', 'create_account', 'deposit', 'transfer', 'accept_transfer', 'top_outgoing'], [[1, 'alice'], [2, 'bob'], [3, 'alice', 100], [4, 'alice', 'bob', 40], [5, 'bob', 'transfer1'], [6, 2]])

Output: [True, True, 100, 'transfer1', True, ['alice', 'bob']]

Example 2

Input: run_bank_ledger(['create_account', 'create_account', 'deposit', 'transfer', 'deposit', 'accept_transfer'], [[1, 'a'], [2, 'b'], [3, 'a', 50], [4, 'a', 'b', 20], [86400004, 'b', 5], [86400005, 'b', 'transfer1']])

Output: [True, True, 50, 'transfer1', 5, False]

Hints

Hint 1

Keep, per account, the available balance (held money already subtracted) and the total of accepted outgoing money. Keep each transfer as a record with source, target, amount, deadline and status.

Hint 2

Because timestamps never decrease, you can keep the deadlines in a min-heap and run one expire routine at the start of every operation except account creation. Pop while the smallest deadline is <= the current timestamp, and skip entries whose status is no longer pending.

Hint 3

For merging, move the source's balance and outgoing total into the destination, then walk the pending transfers. Cancel and refund the destination for ones between the two accounts, and rewrite the source id to the destination id in the rest. Refunds on expiry go to the transfer's current source.