The Hourly Bucket

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L4

Problem

Given a list of event dicts (each with 'ts' in ISO format 'YYYY-MM-DDTHH:MM:SS' and 'type'), group by the hour prefix 'YYYY-MM-DDTHH' (first 13 characters of ts). Return a dict mapping each hour prefix to a list of 'type' values in original order.

Timestamps belong somewhere.

Example

Input:

events = [{"ts":"2024-01-15T14:32:00","type":"click"},{"ts":"2024-01-15T14:55:00","type":"view"},{"ts":"2024-01-15T15:01:00","type":"click"}]

Output:

{"2024-01-15T14":["click","view"],"2024-01-15T15":["click"]}

Worked solution and explanation

Why this problem exists in real interviews

This tests timestamp truncation and grouping, a fundamental operation in log analysis and time-series dashboards. It probes string slicing for ISO timestamps and nested dict accumulation.


Break down the requirements

Step 1: Extract the hour prefix from each timestamp

Slice the ISO timestamp 'YYYY-MM-DDTHH:MM:SS' to 'YYYY-MM-DDTHH' (first 13 characters).

Step 2: Group event types by hour

Build a dict mapping each hour prefix to a list of event type strings in original order.


The solution

Hour-prefix grouping with string slicing
def group_by_hour(events: list) -> dict:
    buckets = {}
    for event in events:
        hour_key = event['ts'][:13]
        event_type = event['type']
        if hour_key not in buckets:
            buckets[hour_key] = []
        buckets[hour_key].append(event_type)
    return buckets

Common follow-up questions