Implement Time-Aware GPU Credit Ledger
Company: OpenAI
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates the ability to design efficient data structures and algorithms for time-aware resource accounting, including handling overlapping grants, ordering by expiration, and maintaining atomic state changes across time.
Constraints
- 0 <= len(operations) <= 2 * 10^5
- 1 <= amount <= 10^9
- 0 <= start_time < expire_time <= 10^9
- 0 <= at_time <= 10^9
- Times in all 'subtract' and 'balance' operations are non-decreasing across the list
Examples
Input: [('create', 10, 0, 10), ('create', 5, 0, 5), ('balance', 0), ('subtract', 7, 3), ('balance', 3), ('balance', 5), ('subtract', 9, 6), ('balance', 6)]
Expected Output: [15, True, 8, 8, False, 8]
Explanation: At time 0 both grants are active, so balance is 15. Subtracting 7 at time 3 must use the grant expiring at 5 first: consume 5 from that grant and 2 from the grant expiring at 10. The remaining active balance is 8. At time 6 only 8 credits remain active, so subtracting 9 fails and state stays unchanged.
Input: [('create', 4, 5, 10), ('balance', 4), ('balance', 5), ('subtract', 2, 7), ('balance', 9), ('balance', 10)]
Expected Output: [0, 4, True, 2, 0]
Explanation: The grant is not active before time 5. It becomes active at time 5, 2 credits are consumed at time 7, 2 remain at time 9, and it is no longer active at time 10.
Input: [('balance', 2), ('create', 6, 1, 5), ('balance', 2), ('subtract', 4, 2), ('balance', 4), ('balance', 5)]
Expected Output: [0, 6, True, 2, 0]
Explanation: The ledger is empty at the first query. When the grant is created, its time window already includes the current time 2, so it becomes immediately active. After subtracting 4, 2 credits remain until expiration at time 5.
Input: [('create', 3, 0, 10), ('create', 4, 0, 10), ('subtract', 8, 1), ('balance', 1), ('subtract', 7, 1), ('balance', 1), ('balance', 9)]
Expected Output: [False, 7, True, 0, 0]
Explanation: Only 7 credits are active at time 1, so subtracting 8 fails and the ledger stays unchanged. The next subtraction of 7 succeeds, leaving no active credits.
Input: []
Expected Output: []
Explanation: No operations produce no results.
Hints
- Because query times never go backward, you can sweep time forward. Each grant only moves from future -> active -> expired once.
- Use a min-heap for active grants ordered by expiration time so subtraction always consumes the earliest-expiring credits first. Keep a running sum of active remaining credits for fast balance queries.