Implement a GPU credit management system class with three methods: (1) add_credit(credit_id, amount, start_ts, expiration_ts) — register a grant of 'amount' credits identified by 'credit_id', valid during the half-open interval [start_ts, expiration_ts); (2) subtract(amount, timestamp) — schedule a deduction of 'amount' credits at the given timestamp, consuming from the earliest-expiring valid grants first; (3) get_balance(timestamp) — compute and return the remaining balance at the given timestamp, or return None (some versions throw InsufficientCreditException) if the effective balance would be negative.
Full problem statement
Implement a GPU credit management system class with three methods: (1) add_credit(credit_id, amount, start_ts, expiration_ts) — register a grant of 'amount' credits identified by 'credit_id', valid during the half-open interval [start_ts, expiration_ts); (2) subtract(amount, timestamp) — schedule a deduction of 'amount' credits at the given timestamp, consuming from the earliest-expiring valid grants first; (3) get_balance(timestamp) — compute and return the remaining balance at the given timestamp, or return None (some versions throw InsufficientCreditException) if the effective balance would be negative. Key constraints: add_credit and subtract calls may arrive with out-of-order timestamps, so all computation must be deferred to get_balance time; only credits whose [start_ts, expiration_ts) window covers the query timestamp are valid; subtract permanently consumes from the earliest-expiring grants (Version II), affecting future balance queries; once get_balance returns None, all subsequent queries also return None regardless of later credit additions. Sample test cases: [subtract(4,30), get_balance(10)→None, add('a',4,20,30), get_balance(10)→0, get_balance(20)→4, get_balance(30)→0] and [add('a',4,20,60), add('b',3,30,40), subtract(2,30), get_balance(30)→5, get_balance(40)→4]. The interviewer provides ~6 test cases; reading them before coding reveals implicit requirements (e.g., expiration boundary semantics, None vs. 0 vs. positive return) not stated in the written description. Two documented variants exist — Version I (subtract is a snapshot deduction not affecting future credits, solvable with sweep-line) and Version II (subtract permanently reduces earliest-expiring grants, requiring event-replay simulation; more commonly seen in interviews).