To solve this problem, we can simulate the actual execution of the functions. For each log, we check if it’s a start or end timestamp — if it’s a start log, then we check if there’s a previous function executing. If so, we want to say its been executing from its timestamp to this timestamp. When we encounter an end, we want to pop the currently executing function and add the previous time to this time.
class Solution:
def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
ans = [0] * n
stack = []
prev_time = 0
for log in logs:
fn_id, action, timestamp = log.split(':')
fn_id, timestamp = int(fn_id), int(timestamp)
if action == "start":
if stack:
ans[stack[-1]] += timestamp - prev_time
stack.append(fn_id)
prev_time = timestamp
else:
ans[stack.pop()] += timestamp - prev_time + 1
prev_time = timestamp + 1
return ans