OpenAI questions

GPU Credit Ledger

OpenAIPhone screenMedium

Build an in-memory ledger of expiring GPU credits for many users. Each grant adds a separate lot of credits that stops being usable at its expiry time; a charge is always taken from the lots that expire soonest. Users never affect each other.

A lot is valid at time t exactly when t < expiry. At t == expiry it is already expired: it does not count toward the balance and cannot be spent.

Every method that takes a time at is called with times that never decrease from one such call to the next, across all users. grant takes no time and can be called at any point.

Each test drives one CreditLedger() instance through a sequence of calls and checks every return value.

Part 1: Grants, charges and balance

Implement:

  • grant(user, amount, expiry) adds a lot of amount credits that expires at expiry. A grant with amount <= 0 is ignored. Returns nothing.
  • charge(user, amount, at) spends amount credits from the lots valid at at, always taking from the lot with the earliest expiry first, using several lots (and part of the last) when needed. If the valid lots hold less than amount in total, it returns False and changes nothing; otherwise it returns True. A charge of 0 always returns True.
  • balance(user, at) returns the total credits in lots valid at at.

A user with no grants has balance 0.

  1. Example 1
    init
    []
    operations
    [["grant",["alice",10,5]],["grant",["alice",30,20]],["charge",["alice",10,5]],["balance",["alice",5]],["charge",["alice",21,6]],["balance",["alice",6]]]
    Output
    [null,null,true,20,false,20]

    Why: The lot of 10 expires at 5, so at time 5 it is already gone: the charge of 10 at time 5 is taken from the 30-lot, leaving 20. The charge of 21 at time 6 needs more than the 20 left, so it fails and changes nothing.

Constraints

  • 1 <= len(operations) <= 2 * 10^4
  • 0 <= amount <= 10^9
  • 0 <= expiry <= 10^9
  • 0 <= at <= 10^9
  • at never decreases across charge and balance calls
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question