Reduce Subscription Events to Latest User Status
SQL & DataAuto-graded · 17 test casesLast updated
Collapse an append-only subscription event log into one status row per user, picking the newest event per user with a deterministic tie-break.
You are given a list of subscription events. Each event is a dict describing a single change to a user's subscription. The log is append-only, so the same user may appear many times: they can sign up, cancel, and later sign up again.
Each event dict has these keys:
user_id(int) -- the user the event belongs to.event_type(str) -- the kind of change, for example"signup"or"cancel". Other values may appear.event_time(str) -- a timestamp formatted as"YYYY-MM-DD HH:MM:SS".plan_type(str, optional) -- the plan the event refers to.source(str, optional) -- where the event came from, for example"web","mobile","email","support".event_id(int, optional) -- a unique identifier for the event.
For every distinct user_id, determine the user's current status by looking only at that user's most recent event. "Most recent" means the greatest event_time; break ties by the greatest event_id, treating a missing event_id as 0. The status is "active" when the winning event's event_type is exactly "signup", and "canceled" for every other event type.
Return a list of dicts, one per user, sorted ascending by user_id. Each dict must have exactly these keys:
"user_id": the user's id."status":"active"or"canceled"as described above."event_time": the winning event'sevent_time, exactly as it appeared in the input string."plan_type": the winning event'splan_type, orNoneif the key is absent (or present with valueNone)."source": the winning event'ssource, orNoneif the key is absent (or present with valueNone).
Notes on edge cases:
- An empty input list returns an empty list.
- A user whose only event is a cancel (no prior signup) is still reported with status
"canceled"; the function reports the newest event and does not validate transition sequences. - Timestamps must be compared as real points in time, not as raw strings, so that ordering is correct even if events arrive out of order in the list.
- If two events for a user share both the same timestamp and the same
event_id(or both lack anevent_id), the one encountered first in the input list is kept.
Constraints:
0 <= len(events) <= 2000001 <= user_id <= 10^9- Every event has a non-empty
event_typestring. - Every
event_timematches"YYYY-MM-DD HH:MM:SS"(a valid calendar date and time). event_id, when present, is a non-negative integer.plan_typeandsource, when present, are strings.- The result is sorted by
user_idascending.
Examples
Example 1
Input: latest_subscription_status([{'user_id': 101, 'event_type': 'signup', 'event_time': '2023-05-01 09:03:12', 'plan_type': 'paid', 'source': 'web', 'event_id': 1}, {'user_id': 101, 'event_type': 'cancel', 'event_time': '2023-06-10 14:27:45', 'plan_type': 'paid', 'source': 'web', 'event_id': 2}, {'user_id': 101, 'event_type': 'signup', 'event_time': '2023-07-02 08:11:06', 'plan_type': 'paid', 'source': 'mobile', 'event_id': 3}, {'user_id': 202, 'event_type': 'signup', 'event_time': '2023-05-05 11:55:20', 'plan_type': 'paid', 'source': 'email', 'event_id': 4}, {'user_id': 303, 'event_type': 'cancel', 'event_time': '2023-05-07 16:02:09', 'plan_type': 'paid', 'source': 'support', 'event_id': 5}])
Output: [{'user_id': 101, 'status': 'active', 'event_time': '2023-07-02 08:11:06', 'plan_type': 'paid', 'source': 'mobile'}, {'user_id': 202, 'status': 'active', 'event_time': '2023-05-05 11:55:20', 'plan_type': 'paid', 'source': 'email'}, {'user_id': 303, 'status': 'canceled', 'event_time': '2023-05-07 16:02:09', 'plan_type': 'paid', 'source': 'support'}]
Example 2
Input: latest_subscription_status([{'user_id': 1, 'event_type': 'signup', 'event_time': '2024-01-01 00:00:00', 'plan_type': 'free_trial', 'source': 'web', 'event_id': 1}, {'user_id': 1, 'event_type': 'cancel', 'event_time': '2024-01-02 00:00:00', 'plan_type': 'free_trial', 'source': 'web', 'event_id': 2}])
Output: [{'user_id': 1, 'status': 'canceled', 'event_time': '2024-01-02 00:00:00', 'plan_type': 'free_trial', 'source': 'web'}]
Hints
Hint 1
You never need to replay the full sequence for a user -- only the single newest event determines the current status.
Hint 2
Build a comparison key from the parsed timestamp plus the event_id (default 0) to decide which event wins for each user.
Hint 3
Parse the timestamps with datetime.fromisoformat so comparisons are chronological, then emit results in sorted user_id order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The current status of a user depends only on their single most recent event, so there is no need to reconstruct the whole signup/cancel sequence. We scan the event list once and, for each user, keep only the event that is greatest under a comparison key.
The key is (parsed_timestamp, event_id). Building the timestamp with datetime.fromisoformat makes comparisons chronological instead of lexicographic, so events listed out of order still resolve correctly. event_id defaults to 0 when it is missing; this guarantees deterministic tie-breaking when two events share a timestamp. We replace the stored record only when the new key is strictly greater than the stored one, which means that on a full tie (same time and same id) the first event seen in the input is kept.
For the retained event, we map "signup" to "active" and every other event type to "canceled". We carry over event_time as the original string, and read plan_type and source with .get so missing keys become None. Finally we output the retained records sorted by user_id.
Why it is correct: for each user, the algorithm stores the maximum-key event under the ordering that defines "most recent" (timestamp first, then event_id, with first-seen winning exact ties). That event is exactly the one the problem designates as latest, so its type maps to the correct status and its fields populate the row. Sorting the distinct user ids yields the required output order.
Complexity: O(n) time to scan the events, plus O(u log u) to sort the u distinct users for output. Space is O(u), one retained record per user.