636. Exclusive Time of Functions

Question

CleanShot 2024-10-30 at 22.19.40.png

Code

class Solution(object):
    def exclusiveTime(self, n, logs):
        res = [0] * n

        prevStart = 0
        stack = []

        for log in logs:
            id_, status, time = log.split(":")

            id_ = int(id_)
            time = int(time)

            if status == "start":
                if stack:
                    res[stack[-1]] += time - prevStart

                stack.append(id_)
                prevStart = time
            else:
	            # since the range is [start, end]
                res[stack.pop()] += time - prevStart + 1
                prevStart = time + 1
        
        return res