Bank app~15 min2s · 256 MBtarget O(q log n) time, O(1) spacebinary-search
A software-as-a-service product stores every subscription's expiry day. Billing keeps the list sorted by expiry, oldest first, so it can work through the list quickly.
Customers get a grace period after the expiry day. A subscription counts as expired on a day only when its expiry day plus the grace period is before that day. Support asks, for many days, how many subscriptions have expired.
Write count_expired(expiries, days, grace).
expiries is sorted from the smallest to the largest. Equal values are allowed.e is expired on day d when e + grace < d.days, count the expired subscriptions on that day.days. The days are in any order.Input: expiries = [3, 8, 8, 15, 20, 41], days = [2, 9, 10, 50, 12], grace = 2
Output: [0, 1, 1, 6, 3]With grace = 2, a subscription is expired on day d when its expiry is below d - 2. The trace counts the subscriptions below that cutoff.
| Day | Cutoff (day - 2) | Expiries below the cutoff | Count |
|---|---|---|---|
| 2 | 0 | none | 0 |
| 9 | 7 | 3 | 1 |
| 10 | 8 | 3 (the two 8s are not below 8) | 1 |
| 50 | 48 | all six | 6 |
| 12 | 10 | 3, 8, 8 | 3 |
The output is [0, 1, 1, 6, 3].
Input: expiries = [5], days = [5, 6], grace = 0
Output: [0, 1]With no grace, a subscription expiring on day 5 is not expired on day 5, only from day 6.
Input: expiries = [0, 0, 0], days = [0, 1], grace = 5
Output: [0, 0]All three subscriptions expire on day 0, but with a grace of 5 none is expired on day 0 or day 1.
1 ≤ expiries.length ≤ 100,000 (subscriptions), sorted in non-decreasing order0 ≤ expiries[i] ≤ 1,000,000,000 (days since the product launched)1 ≤ days.length ≤ 100,000 (queried days), 0 ≤ days[q] ≤ 1,000,000,0000 ≤ grace ≤ 1,000 (days)Scanning every subscription for every queried day costs about n × q, about 10^10 steps. The list is sorted, so the subscriptions below a cutoff are a prefix of it. Binary search finds the end of that prefix in about 17 steps, and the length of the prefix is the answer.