636. Exclusive Time of Functions - cocoder39/coco39_LC GitHub Wiki

636. Exclusive Time of Functions

2024:

when there is an end event, first pair it with the start event of same function id in stack. if stack is still not empty, it means current function is called inside another function. so the time spent on current function should be excluded from the parent function

  • how to deduct the current duration from parent function?
    • option 1: update parent function timestamp in stack: if parent function is within another function, this could impact the calculation of the grandparent function
    • option 2: update function_time for parent function: no side effect
class Solution:
    def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
        
        function_time = [0] * n
        stack = []
        for log in logs:
            tokens = log.split(':')
            function_id = int(tokens[0])
            function_type = tokens[1]
            timestamp = int(tokens[2])
            
            if function_type == 'start':
                stack.append((function_id, timestamp))
            else:
                _, start_timestamp = stack.pop()
                duration = timestamp - start_timestamp + 1
                function_time[function_id] += duration
                if stack:
                    parent_function_id = stack[-1][0] 
                    function_time[parent_function_id] -= duration 
        return function_time

stack[-1] is always the active function even if there are recursion calls

class Solution:
    def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
        time = [0] * n
        stack = []
        start_time = 0 # start time of the active function
        
        for log in logs:
            function_id, state, timestamp = log.split(':')
            function_id = int(function_id)
            timestamp = int(timestamp)
            if state == 'start':
                if stack:
                    time[stack[-1]] += timestamp - start_time
                stack.append(function_id)
                start_time = timestamp
            else:
                stack.pop()
                time[function_id] += timestamp + 1 - start_time
                start_time = timestamp + 1
        
        return time