LC 0636 [M] Exclusive Time of Functions - ALawliet/algorithms GitHub Wiki

idea

if a1 => b => a2,
then a_time = ((a2 - a1) + 1) - b

like cur is a window, then exclude prev

walkthru

[0,0] :
[0,0] [1,2] :
[0,0] : ans[1] (0) += (5-2)+1 = 4, ans[0] -= (5-2)+1 = -4
: ans[0] (-4) += (6-0)+1=7 = 3   
class Solution:
    def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
        stack = []
        exclusive_time = [0] * n
        
        for log in logs:
            r, action, r_time = log.split(':')
            r, r_time = int(r), int(r_time)
            
            if action == 'start':
                stack.append( (r, r_time) ) # )

            elif action == 'end': # close the parens
                l, l_time = stack.pop() # (

                execution_time = r_time - l_time + 1 # (...) inclusive +1 for current unit, like r - l + 1

                exclusive_time[l] += execution_time # ( -> ...
                
                if stack: # decrement last 
                    k_id, _ = stack[-1] # k(...), k is unrelated to r or l, but remains the last exclusive_time window was claimed
                    exclusive_time[k_id] -= execution_time # k, slide the left part of window up
                    
        return exclusive_time