Coupon Usage Caps: Check Remaining Redemptions per User
Arrays & HashingAuto-graded · 16 test casesLast updated
Count past coupon redemptions per (user, coupon) pair from a log, then answer many read-only queries on whether each user is still under the coupon's cap.
Coupon Usage Caps
A checkout service enforces a cap on how many times each customer may use each coupon. You are given the cap for every known coupon, a history of redemptions that have already happened, and a batch of eligibility questions.
Task
Implement check_coupon_eligibility(coupon_caps, redemption_history, queries).
coupon_caps: a dictionary mapping a coupon identifier (string) to an integer, the maximum number of times a single user may redeem that coupon.redemption_history: a list of dictionaries, each with the keysuser_id(string),promo_id(string) andtimestamp(non-negative integer). Each entry records one completed redemption of couponpromo_idby useruser_id.queries: a list of dictionaries, each with the keysuser_idandpromo_id.
Return a list of booleans with one entry per query, in the same order as queries. An entry is True if the number of history entries for that exact (user_id, promo_id) pair is strictly less than the cap for that coupon, and False otherwise.
Rules
- Every history entry counts toward usage, regardless of its timestamp. Timestamps do not affect the answer, and the history is not guaranteed to be sorted.
- Duplicate history entries (even with identical user, coupon and timestamp) each count separately.
- A query is a read-only check. Answering it does not add a redemption, so identical queries always get identical answers.
- If a user has no history entries for a coupon, their usage is 0.
- If a coupon is not present in
coupon_caps, its cap is 0, so the answer is alwaysFalse, even if the history contains entries for it. - A cap of 0 (or less) means nobody is ever eligible.
- If
queriesis empty, return an empty list.
Constraints
redemption_historyandquerieseach contain up to 10^5 entries.timestampis a non-negative integer.- A single user may have a very large number of history entries.
- Your solution should comfortably run within time limits for the largest inputs.
Examples
Example 1
Input: check_coupon_eligibility({'SAVE10': 2, 'WELCOME': 1}, [{'user_id': 'u1', 'promo_id': 'SAVE10', 'timestamp': 100}, {'user_id': 'u1', 'promo_id': 'SAVE10', 'timestamp': 150}, {'user_id': 'u2', 'promo_id': 'WELCOME', 'timestamp': 200}], [{'user_id': 'u1', 'promo_id': 'SAVE10'}, {'user_id': 'u1', 'promo_id': 'WELCOME'}, {'user_id': 'u2', 'promo_id': 'WELCOME'}])
Output: [False, True, False]
Hints
Hint 1
Re-scanning the whole history for each query would take about 10^10 steps in the worst case. Think about preprocessing the history once.
Hint 2
Group usage by the pair (user_id, promo_id). A tuple works well as a dictionary key, and each history entry adds one to its pair's count.
Hint 3
When answering a query, use a default of 0 for a pair never seen and a default of 0 for a coupon missing from the caps, then compare with a strict less-than. Do not modify counts while answering.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a counting problem. Aggregate the history once, then answer every query with constant-time lookups.
- Walk through
redemption_historyonce and build a dictionary keyed by the tuple(user_id, promo_id). Each entry adds one to its pair's count. Timestamps are ignored and no sorting is needed. - For each query, read the pair's count (default 0 if the pair never appears) and the coupon's cap (default 0 if the coupon is unknown). The answer is
count < cap.
Queries never modify the counts, so repeated queries are answered identically.
Why it is correct
- After the first pass, the count for
(u, p)equals the number of history entries with that user and coupon, since each entry increments exactly one key by one. Duplicates are counted individually, as required. - A pair absent from the history has usage 0, which the default supplies.
- An unknown coupon gets cap 0. Because counts are never negative,
count < 0is always false, so such coupons are never eligible, even if the history mentions them. - The strict inequality gives the right boundary: a user who has used exactly as many times as the cap is not eligible, while one use below the cap is.
- Caps of 0 or below can never exceed a non-negative count, so they also yield
False.
Complexity
Let E be the number of history entries and Q the number of queries.
- Time: O(E + Q) on average, with one hash update per entry and two hash lookups per query.
- Space: O(K + Q), where K is the number of distinct (user, coupon) pairs in the history and Q is the size of the output list.
The naive alternative of scanning the entire history for each query costs O(E * Q), which is too slow at the stated limits.
Reference solution
from typing import Dict, List
def check_coupon_eligibility(coupon_caps: Dict[str, int], redemption_history: List[Dict[str, object]], queries: List[Dict[str, object]]) -> List[bool]:
usage = {}
for entry in redemption_history:
key = (entry["user_id"], entry["promo_id"])
usage[key] = usage.get(key, 0) + 1
return [
usage.get((q["user_id"], q["promo_id"]), 0)
< coupon_caps.get(q["promo_id"], 0)
for q in queries
]