Space
Open
From Fieldwork
Scales
Archive
It’s an event-driven simulation. Instead of "ticking" a clock second by second (which would be super slow if a function ran for a billion seconds), we only care about the moments when the status quo changes.
class Solution:
def exclusiveTime(self, n, logs):
# ans stores the exclusive time for each function ID
ans = [0] * n
stack = [] # Stores function IDs
# prev_time keeps track of the last timestamp we processed
prev_time = 0
for log in logs:
# Parse the log string
fn_id, type, timestamp = log.split(':')
fn_id, timestamp = int(fn_id), int(timestamp)
if type == 'start':
# If there's a function already running,
# add the time elapsed to its exclusive count
if stack:
ans[stack[-1]] += timestamp - prev_time
# Push current function and update current time
stack.append(fn_id)
prev_time = timestamp
else: # type == 'end'
# Pop the function and add the duration (inclusive)
# +1 because "end at 2" means the function ran through the end of second 2
popped_id = stack.pop()
ans[popped_id] += timestamp - prev_time + 1
# Update prev_time to the start of the next second
prev_time = timestamp + 1
return ansPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode