The Event Bucketer
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L5
- Asked in
- Meta
Problem
hourly_event_counts is given logs, a list of [timestamp, label] pairs from a product's clickstream, and returns, for each hour bucket, how many times each event label fired in it. Timestamps are 'YYYY-MM-DD HH:MM:SS' strings, and a bucket is named by its date and hour, as in '2024-03-15 09'. The same hour on two different days is two separate buckets.
Logs slotted into buckets.
Example 1
Input:
logs = [["2024-03-15 09:12:00","click"],["2024-03-15 09:45:00","click"],["2024-03-15 09:30:00","view"],["2024-03-15 10:05:00","click"]]
Output:
{"2024-03-15 09":{"view":1,"click":2},"2024-03-15 10":{"click":1}}Example 2
Input:
logs = []
Output:
{}Worked solution and explanation
Why this problem exists in real interviews
This tests two-level grouping: bucketing events by hour, then counting by event type within each bucket. It probes nested dict accumulation and timestamp slicing skills.
Break down the requirements
Step 1: Extract the hour prefix from each timestamp
Each log is a [timestamp, event_type] pair. Slice the timestamp's first 13 characters (timestamp[:13]) to get the YYYY-MM-DD HH bucket key.
Step 2: Group events by hour bucket
Initialize the outer dict for an unseen hour bucket, then the inner dict's event type count, before incrementing. This is the nested-dict accumulation pattern.
Step 3: Count event types within each bucket
For each hour, increment the count for its event type. Each log entry contributes exactly one count to one bucket and one event type.
The solution
def hourly_event_counts(logs: list) -> dict:
buckets = {}
for timestamp, event_type in logs:
hour_key = timestamp[:13]
if hour_key not in buckets:
buckets[hour_key] = {}
if event_type not in buckets[hour_key]:
buckets[hour_key][event_type] = 0
buckets[hour_key][event_type] += 1
return bucketsCommon follow-up questions
- How would you handle time zones? (Tests converting to UTC before bucketing.)
- What if you needed 15-minute buckets instead of hourly? (Tests floor-division on the minute component.)
- How would you stream this for real-time dashboards? (Tests incremental updates vs batch recomputation.)