Exclusive Time of Functions — LeetCode 636 Python Solution

MediumStackArray
Problem
#636
Pattern
Stack
Reading time
3 min

The problem

On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1.

Example

Input
n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]
Output
[3,4]
Explanation
Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.

Python solution

Python
class Solution:
    def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
        stk = []
        ans = [0] * n
        pre = 0
        for log in logs:
            i, op, t = log.split(":")
            i, cur = int(i), int(t)
            if op[0] == "s":
                if stk:
                    ans[stk[-1]] += cur - pre
                stk.append(i)
                pre = cur
            else:
                ans[stk.pop()] += cur - pre + 1
                pre = cur + 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 636. Exclusive Time of Functions is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 636. Exclusive Time of Functions?
LeetCode 636. Exclusive Time of Functions is rated Medium on LeetCode.
What is the time complexity of LeetCode 636. Exclusive Time of Functions?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 636. Exclusive Time of Functions?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 636. Exclusive Time of Functions cover?
LeetCode 636. Exclusive Time of Functions is tagged Stack and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview