Monitoring~15 min2s · 256 MBtarget O(n + d) time, O(n) spacehashing
A team reads the event logs of a software product to track retention. Each activity event records the day and the user who did something. A user may cause many events in a day.
The team wants a returning-user count for each day: how many users were active that day and also active the day before. A quiet day in between breaks the streak.
Write returning_users(days, users, total_days).
i says that user users[i] was active on day days[i]. The events are in any order and may repeat.d when they have an event on day d and an event on day d - 1.total_days numbers. Entry d is the number of returning users on day d, counting each user once. Day 0 has no day before it, so its entry is 0.Input: days = [0, 0, 1, 1, 1, 2, 2, 3], users = [7, 8, 7, 9, 7, 9, 10, 10], total_days = 5
Output: [0, 1, 1, 1, 0]The trace keeps the set of users for each day.
| Day | Users active that day | Active the day before | Returning users | Count |
|---|---|---|---|---|
| 0 | 7, 8 | none | none | 0 |
| 1 | 7, 9 | 7, 8 | 7 | 1 |
| 2 | 9, 10 | 7, 9 | 9 | 1 |
| 3 | 10 | 9, 10 | 10 | 1 |
| 4 | none | 10 | none | 0 |
The output is [0, 1, 1, 1, 0]. Day 4 has no events, so it has no returning users.
Input: days = [0, 2], users = [1, 1], total_days = 3
Output: [0, 0, 0]User 1 was active on days 0 and 2, but not on day 1, so they are never returning.
Input: days = [0, 0, 0, 1, 1], users = [5, 5, 5, 5, 5], total_days = 2
Output: [0, 1]User 5 caused three events on day 0 and two on day 1. They count once on day 1, so the answer is 1.
1 ≤ days.length ≤ 100,000 (activity events); users has the same length0 ≤ days[i] ≤ 999 (day numbers); 1 ≤ users[i] ≤ 1,000,000,000 (user ids)1 ≤ total_days ≤ 1,000; every days[i] is below total_daysScanning all events for every day costs about days × n, up to 10^8 steps, and comparing the users of two days by scanning again is worse. One pass puts each user in the set of their day. A second pass compares each set with the previous one. Together they cost about n.