Exclusive Time of Functions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
        result = [0] * n
        stack = []  # To keep track of function calls

        for log in logs:
            parts = log.split(":")
            func_id = int(parts[0])
            action = parts[1]
            timestamp = int(parts[2])

            if action == "start":
                if stack: # If there is a function call in the stack
                    result[stack[-1][0]] += timestamp - stack[-1][1]
                stack.append([func_id, timestamp])  # Add the current function call to the stack
            else:  # action is "end"
                _, start_time = stack.pop()  # Get the starting time of the ending function call
                time_spent = timestamp - start_time + 1
                result[func_id] += time_spent
                if stack:  # If there is still a function call in the stack, update its starting time
                    stack[-1][1] = timestamp + 1

        return result