26/40
Part 6 of 8 · Lazy deletesLearn and do

A credit heap keyed by expiry drops each expired credit when it reaches the top

The practice problem's credits sit in a heap keyed by expiry. Tuples can't be changed, so entries that change are lists: [expires, count, credit_id, left].

When a spend looks at the top and finds a credit that has expired, it drops it and looks again, at O(log n) per drop. A credit that's partly used stays on top with less left. That's safe, because the amount left isn't part of the key.

Here a spend of 60 at time 12 meets three credits. Each row is one look at the top:

TopExpires, leftWhat happensStill to pay
trial10, 20expired, since 10 <= 12: pop it60
promo30, 50pays 50, stays on top10
promo30, 0nothing left: pop it10
basenever, 100pays 10, stays on top with 900

A credit used up exactly can stay in the heap with 0 left, until the next spend reaches it. That's lazy deletion again. Anything that adds up the balance has to skip it, or simply add its 0. Popping it the moment it hits 0 works just as well.

In the editor, write spend(heap, amount, now), the spend from the table. Look at the top credit again and again: drop it if it has expired or is empty, and otherwise take what it can pay. Return the part nothing could pay.