Katkat

Compute total active time per Twitter Space

xAISoftware Engineer · Onsite

Last updated

This problem tests your ability to process chronological event streams to calculate overlapping or continuous active intervals and aggregate durations per category.

Problem Statement

You are given a list of events representing user activity in various Twitter Spaces. Each event is a dictionary containing user_id, space_id, action ("join" or "leave"), and a timestamp (integer).

A user is considered "active" in a specific Space from the moment they "join" until they "leave". If a user joins multiple times without leaving, or leaves without a corresponding join, ignore the malformed sequence for that specific user-space pair (i.e., only count completed intervals where join occurs before leave).

Your task is to write a function calculate_total_active_time(events) that returns a dictionary where keys are space_id and values are the total duration all users spent in that space.

Function Signature

def calculate_total_active_time(events):
    # events is a list of dicts: {'user_id': int, 'space_id': str, 'action': str, 'timestamp': int}
    pass

Constraints

  • 1 <= len(events) <= 10^5
  • Timestamps are non-negative integers.
  • Multiple users can be in the same space simultaneously.

Examples

events = [
    {'user_id': 1, 'space_id': 'A', 'action': 'join', 'timestamp': 10},
    {'user_id': 1, 'space_id': 'A', 'action': 'leave', 'timestamp': 20},
    {'user_id': 2, 'space_id': 'A', 'action': 'join', 'timestamp': 15},
    {'user_id': 2, 'space_id': 'A', 'action': 'leave', 'timestamp': 25}
]
# Result: {'A': 20} 
# Explanation: User 1: 10 units (20-10). User 2: 10 units (25-15). Total = 20.

Edge Cases

  • Events out of order: You must sort the events by timestamp first.
  • Missing "join" or "leave" pairs.
  • Multiple spaces or users appearing in the stream.

Hints

Hint 1

Sort the events by timestamp to ensure chronological processing.

Hint 2

Use a hash map to track the current 'join' timestamp for each user within each specific space.

Hint 3

Only accumulate the duration when a 'leave' event follows a valid 'join' event for the same user in the same space.

Follow-up questions

  • How would you modify your solution if multiple 'join' events occurred without an intervening 'leave'? Should you update the start time or ignore the second join?
  • If the input volume is massive (e.g., billions of events), how would you parallelize this calculation across a distributed system?
  • How does your solution handle 'leave' events that occur before any 'join' for a specific user-space pair?