Event Log Analysis: Distinct Users and Session Duration
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests grouping, deduplication, and timestamp arithmetic over semi-structured event records.
Event Log Analysis
You receive a list of event records from a web application. Each record is a dictionary with three fields:
user_id(int): the identifier of the user who triggered the event.timestamp(str): when the event occurred, in the format'YYYY-MM-DD HH:MM:SS'(24-hour notation, single time zone, no offset markers).activity(str): a label describing the event type, such as'login','view','purchase', or'logout'.
Your function receives this list and must return a dictionary containing two computed metrics:
{
"unique_users_per_activity": { ... },
"average_time_per_user_seconds": ...
}
Metric 1: Unique users per activity
Build a mapping where each key is an activity label and each value is the number of distinct users who performed that activity at least once. If a single user performs the same activity multiple times, count that user only once for that activity.
Metric 2: Average session duration per user
For each user, compute their session duration as the difference in seconds between their earliest and latest recorded events. A user who appears in only one record has a duration of 0 seconds.
Return the mean of these per-user durations across all distinct users, as a float (in seconds).
Example
Given:
[
{'user_id': 1, 'timestamp': '2024-07-26 10:00:00', 'activity': 'login'},
{'user_id': 2, 'timestamp': '2024-07-26 10:05:00', 'activity': 'login'},
{'user_id': 1, 'timestamp': '2024-07-26 10:10:00', 'activity': 'view'},
{'user_id': 1, 'timestamp': '2024-07-26 10:15:00', 'activity': 'purchase'},
{'user_id': 2, 'timestamp': '2024-07-26 10:20:00', 'activity': 'view'},
{'user_id': 3, 'timestamp': '2024-07-26 10:25:00', 'activity': 'login'},
{'user_id': 1, 'timestamp': '2024-07-26 10:30:00', 'activity': 'logout'},
]
Metric 1: login was performed by users 1, 2, and 3; view by users 1 and 2; purchase by user 1; logout by user 1.
{'login': 3, 'view': 2, 'purchase': 1, 'logout': 1}
Metric 2:
- User 1: earliest at
10:00:00, latest at10:30:00→ 1800 seconds - User 2: earliest at
10:05:00, latest at10:20:00→ 900 seconds - User 3: single event → 0 seconds
Average: (1800 + 900 + 0) / 3 = 900.0
Return:
{
"unique_users_per_activity": {'login': 3, 'view': 2, 'purchase': 1, 'logout': 1},
"average_time_per_user_seconds": 900.0
}
Constraints
0 ≤ len(user_activity) ≤ 10⁵- Records may arrive in any order (not sorted by timestamp).
user_idis a positive integer.- All timestamps are valid and follow the format
'YYYY-MM-DD HH:MM:SS'. - Activity labels are non-empty strings.
- When the input is empty, return
{"unique_users_per_activity": {}, "average_time_per_user_seconds": 0.0}. - A user with exactly one event contributes
0to the numerator and1to the denominator of the average.
Examples
Example 1
Input: user_activity_analytics([{'user_id': 1, 'timestamp': '2024-07-26 10:00:00', 'activity': 'login'}, {'user_id': 2, 'timestamp': '2024-07-26 10:05:00', 'activity': 'login'}, {'user_id': 1, 'timestamp': '2024-07-26 10:10:00', 'activity': 'view'}, {'user_id': 1, 'timestamp': '2024-07-26 10:15:00', 'activity': 'purchase'}, {'user_id': 2, 'timestamp': '2024-07-26 10:20:00', 'activity': 'view'}, {'user_id': 3, 'timestamp': '2024-07-26 10:25:00', 'activity': 'login'}, {'user_id': 1, 'timestamp': '2024-07-26 10:30:00', 'activity': 'logout'}])
Output: {'unique_users_per_activity': {'login': 3, 'view': 2, 'purchase': 1, 'logout': 1}, 'average_time_per_user_seconds': 900}
Example 2
Input: user_activity_analytics([])
Output: {'unique_users_per_activity': {}, 'average_time_per_user_seconds': 0}
Example 3
Input: user_activity_analytics([{'user_id': 7, 'timestamp': '2024-01-02 12:00:00', 'activity': 'view'}, {'user_id': 7, 'timestamp': '2024-01-02 11:00:00', 'activity': 'view'}, {'user_id': 8, 'timestamp': '2024-01-02 11:30:00', 'activity': 'login'}, {'user_id': 7, 'timestamp': '2024-01-02 12:00:00', 'activity': 'view'}])
Output: {'unique_users_per_activity': {'view': 1, 'login': 1}, 'average_time_per_user_seconds': 1800}
Hints
Hint 1
Use a set for each activity to automatically deduplicate user IDs as you scan the records.
Hint 2
Track the minimum and maximum timestamp for each user to compute their session duration without sorting.
Hint 3
Parse timestamps with datetime.strptime and use .total_seconds() on the difference to get a float duration.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both metrics can be computed in a single pass over the event records using group-by aggregations:
Metric 1 (distinct users per activity): Maintain a dictionary mapping each activity to a set of user IDs. Sets automatically handle deduplication, so if user 1 performs 'view' five times, the set for 'view' contains 1 only once. After processing all records, the size of each set gives the count of distinct users for that activity.
Metric 2 (average session duration): Track the earliest and latest timestamp for each user. Initialize both to the first observed timestamp for that user, then update the minimum if a record arrives with an earlier timestamp and update the maximum if a record arrives with a later timestamp. This running min/max approach works regardless of input order and avoids the cost of sorting. Once all records are processed, compute each user's duration as (latest - earliest).total_seconds(), then average these durations across all users.
Parse timestamps using datetime.strptime with the format "%Y-%m-%d %H:%M:%S". Subtracting two datetime objects yields a timedelta, and calling .total_seconds() converts it to a float representing seconds.
Edge cases:
- Empty input: return
{}for the activity mapping and0.0for the average to avoid division by zero. - Single-event user: duration is
0seconds, but the user still counts in the denominator. - Duplicate
(user_id, activity)pairs: the set deduplicates automatically. - Out-of-order records: the running min/max is order-independent.
Why It Works
After the loop completes:
users_by_activity[activity]contains every distinct user who performed that activity at least once.user_times[user_id]holds[earliest, latest]timestamps for that user across all their events.
The invariant is maintained on every record: if a timestamp is earlier than the stored minimum, update it; if later than the stored maximum, update it. This correctly captures the global earliest and latest for each user.
Averaging over users (not records) matches the specification. A user who appears once contributes 0 to the sum and 1 to the count, which is correct.
Complexity
Time: O(n), where n is the number of records. Each record requires one timestamp parse (constant time for fixed-length strings), one set insertion, and constant-time dictionary operations. Building the final counts is O(A) for A distinct activities, and summing durations is O(U) for U distinct users; both are bounded by n.
Space: O(n) in the worst case. The activity sets together hold at most one entry per distinct (activity, user_id) pair, which is at most n. The user times dictionary holds O(U) entries.
Solution
from datetime import datetime
def user_activity_analytics(user_activity):
users_by_activity = {}
user_times = {}
fmt = "%Y-%m-%d %H:%M:%S"
for record in user_activity:
user_id = record["user_id"]
activity = record["activity"]
timestamp = datetime.strptime(record["timestamp"], fmt)
users_by_activity.setdefault(activity, set()).add(user_id)
if user_id not in user_times:
user_times[user_id] = [timestamp, timestamp]
else:
if timestamp < user_times[user_id][0]:
user_times[user_id][0] = timestamp
if timestamp > user_times[user_id][1]:
user_times[user_id][1] = timestamp
unique_counts = {
activity: len(users)
for activity, users in users_by_activity.items()
}
if not user_times:
average_time = 0.0
else:
total_seconds = sum(
(last - first).total_seconds()
for first, last in user_times.values()
)
average_time = total_seconds / len(user_times)
return {
"unique_users_per_activity": unique_counts,
"average_time_per_user_seconds": average_time,
}