Twitter Spaces is a live audio feature where users can create rooms, join conversations, and leave at any time. Given a log of operations, compute the total active time for each Twitter Space.
You are given a list of logs where each log is a string that contains a type of operation and a timestamp. The operations are:
"join": The user with ID uid joined a Twitter Space with ID sid at time t."leave": The user with ID uid left a Twitter Space with ID sid at time t.Design an algorithm to compute the total active time for each Twitter Space, which is the sum of the duration each user spent in the space.
Input:
logs = ["join uid1 sid1 1", "join uid2 sid1 2", "join uid1 sid2 3", "leave uid2 sid1 5", "leave uid1 sid2 6"]
Output:
{"sid1": 5, "sid2": 3}
Input:
logs = ["join uid1 sid1 1", "join uid2 sid1 2", "join uid3 sid2 3", "join uid4 sid2 4", "join uid2 sid3 5", "leave uid1 sid1 8", "leave uid2 sid1 9", "leave uid3 sid2 10", "leave uid4 sid2 11", "leave uid2 sid3 12"]
Output:
{"sid1": 7, "sid2": 7, "sid3": 7}
1 <= logs.length <= 10^41 <= uid, sid, t <= 100`python def computeActiveTime(logs): # Initialize data structures space_users = {} active_time = {}
# Process each log
for log in logs:
op, uid, sid, t = log.split()
t = int(t)
if op == "join":
if sid not in space_users:
space_users[sid] = {}
space_users[sid][uid] = t
elif op == "leave":
if sid not in space_users or uid not in space_users[sid]:
continue
start_time = space_users[sid].pop(uid)
if sid not in active_time:
active_time[sid] = 0
active_time[sid] += t - start_time
return active_time
`
This solution has a time complexity of O(n), where n is the number of logs, and a space complexity of O(u + s), where u is the number of unique users and s is the number of unique spaces.