Daily per-user event counts
Python data engineering interview problem. Difficulty: intermediate. Pattern: Dictionaries. About 16 minutes. Part of the Pro drill bank.
Count events per user per day and per type from out-of-order data that contains replayed events. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
Event streams can arrive out of order and can replay the same event. A daily report must be deterministic and must not double-count a replay. Deduplicate by event_id, extract the date from each timestamp, count types per user and date, then sort records by user and date. Write daily_counts(events: list[dict]) -> list[dict]. The repeated e1 click is counted once, while e2 is a view on the next day, producing 1 record for each date. The starter file already contains the function name, harness and print lines. Keep them and fill only the function body.
Requirements
- Count each event_id once.
- Group by user and calendar date.
- Return sorted records with a nested type-count dictionary.
Constraints
- Timestamps are ISO strings and events may be out of order.
- The input must not change and the return type is a list of dicts.
Examples
Input: daily_counts([{"event_id": "e2", "user": "u1", "ts": "2024-05-02T09:00:00", "type": "view"}, {"event_id": "e1", "user": "u1", "ts": "2024-05-01T10:00:00", "type": "click"}, {"event_id": "e1", "user": "u1", "ts": "2024-05-01T10:00:00", "type": "click"}]) Output: [{'user': 'u1', 'date': '2024-05-01', 'counts': {'click': 1}}, {'user': 'u1', 'date': '2024-05-02', 'counts': {'view': 1}}] The second e1 is a replay and is ignored; the 2 days are reported in date order even though the input was not sorted.
Topics: lakebench, python, dedupe, group by, idempotent.
More Python interview questions · All interview problems · Learn data engineering
Daily per-user event counts
Interview-style drill: Count events per user per day and per type from out-of-order data that contains replayed events.
Implement `daily_counts(events: list[dict]) -> list[dict]`. Each event is `{"event_id", "user", "ts", "type"}` where `ts` is an ISO timestamp like `"2024-05-01T10:00:00"`. Events arrive in any order, and the same `event_id` can appear more than once (a replay): count it once. Return 1 record per `(user, date)`: `{"user": ..., "date": "YYYY-MM-DD", "counts": {type: number, ...}}`. Sort records by user, then date. Calling the function twice on the same input must give the same output, and the input list must not change.