Exclusive Time of Functions LeetCode solution in Python

1
# Runtime: 78 ms (Top 92.98%) | Memory: 14.2 MB (Top 33.69%)
2
class Solution:
3
# T=O(n), S=O(d)
4
# n=len of logs, d=depth of stack
5
def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
6
# init result array to zeroes of length n (function ids)
7
res = [0] * n
8
stack = []
9
# iterate through logs
10
for log in logs:
11
# split the log
12
# function_id: start|end: timestamp
13
log = log.split(":")
14
# type cast function id and timestamp to int type
15
id = int(log[0])
16
timestamp = int(log[2])
17
state = log[1]
18
# detect start of a function call
19
# stack[function_id, start_timestamp]
20
if state == "start":
21
# stack is non empty
22
if stack:
23
# get the time taken by last function so far
24
res[stack[-1][0]] += timestamp - stack[-1][1]
25
# append the current function_id and start timestamp to the stack
26
stack.append([id, timestamp])
27
else:
28
# get the time consumed by current function
29
# dont forget to add 1 as the last unit of time should be included
30
res[id] += timestamp - stack.pop()[1] + 1
31
if stack:
32
# update the start time of last function in stack to get the cumulative result
33
stack[-1][1] = timestamp + 1
34

35
return res

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0