1751. Expiring Coupons Desk

Medium3.5 points estimatedDesignHeapHash Table

A shopping app keeps a pool of discount coupons at its checkout desk. Implement a class CouponDesk with a no-argument constructor. add(id, price, expiry) stores a coupon with a brand-new id; the coupon costs the customer price points and is valid only while the current time is strictly less than expiry. use(id) consumes that coupon; an id that was never added, or is already consumed, is ignored. cheapest(now) returns the id of the unused coupon with expiry > now and the lowest price (the smaller id when prices tie), or -1 if no coupon qualifies; it does not consume anything. Across calls to cheapest, the value of now never decreases. Aim for O(log n) amortised time per call and O(n) space. There are at most 2 * 10^4 calls and all numbers lie between 1 and 10^9.

Example 1

Input:
operations = ["CouponDesk","add","add","add","cheapest","use","cheapest","cheapest"]arguments = [[],[1,50,10],[2,30,5],[3,30,8],[1],[2],[2],[3]]
Output:
[null,null,null,null,2,null,3,3]
Explanation:

Coupons 2 and 3 both cost 30, so the smaller id 2 wins; after coupon 2 is used the answer is 3; at time 3 coupon 3 is still valid and cheapest.

Example 2

Input:
operations = ["CouponDesk","add","add","cheapest","cheapest","use","cheapest"]arguments = [[],[7,20,4],[9,15,6],[3],[4],[9],[5]]
Output:
[null,null,null,9,9,null,-1]
Explanation:

At time 3 coupon 9 (price 15) is cheapest; at time 4 coupon 7 has expired but 9 remains; after using 9 nothing is left at time 5, so the answer is -1.

Constraints

At most 2 * 104 calls in total; ids are unique across add calls; 1 ≤ id, price, expiry, now ≤ 109; now is non-decreasing across cheapest calls.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Input
Each case is an operation log. operations names the class first and then each method call; arguments holds the arguments for each, in the same order. Your answer is one list with a result per operation - null for the constructor and for methods that return nothing.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(log n) amortised per call
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…

operations names the class, then each method to call; arguments holds one list of arguments per operation, in the same order.