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

Given log tuples [timestamp_string, event_label] where timestamp is 'YYYY-MM-DD HH:MM:SS', bucket by hour using the first 13 characters ('YYYY-MM-DD HH'). Return a dict mapping each hour bucket to a dict mapping each event label to its count within that hour. An empty input list returns an empty dict {}.

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

Two-level grouping with hour truncation
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 buckets

Common follow-up questions