Problem Statement

Exclusive Time of Functions

A computer runs n small programs called functions, one at a time. Each function has its own number, from 0 up to n-1. We are handed a list of logs. Each log is a short string like "id:start|end:timestamp", which tells us a function either started or ended at a certain moment in time. We want the exclusive time of each function: how long it actually spent running on its own, not counting time where it called another function and waited for that one to finish. The trick here is a stack. A stack is like a pile of plates: you only add a plate to the top, and you only take a plate from the top. The last plate you put on is the first one you take off. That matches how function calls work perfectly. When function A calls function B, A pauses and B goes on top of the pile. When B finishes, it comes off the top and A resumes. So the stack tells us, at any moment, which function is the one truly running right now (the plate on top).

mediumStackStackTime: O(n) · Space: O(n)

Signals to notice

track execution time of nested function callsexclusive time per functionstack for call hierarchy

Brute force first

Not applicable — the stack approach IS the natural solution for nested calls.

The key insight

Stack of function IDs. On start: push function, record timestamp. On end: pop, compute duration, subtract from parent's time. O(n).

Trace it on n=2, logs=["0:start:0","1:start:2","1:end:5","0:end:6"]

init: result=[0,0], stack=[], prev=0
"0:start:0": stack empty, push 0 -> stack=[0], prev=0
"1:start:2": stack top=0, result[0]+=2-0=2 -> result=[2,0]; push 1 -> stack=[0,1], prev=2
"1:end:5": pop 1, result[1]+=5-2+1=4 -> result=[2,4]; prev=5+1=6
"0:end:6": pop 0, result[0]+=6-6+1=1 -> result=[3,4]; prev=6+1=7
return [3,4]

What must stay true

The stack represents the active call chain. When a function ends, its duration is added to its total. The parent function's exclusive time excludes child durations.

Shape of the loop

result = [0]*n; stack = []; prev = 0
for (id, typ, t) in parsed(logs):
  if typ == start:
    if stack: result[stack.top] += t - prev
    stack.push(id); prev = t
  else:  # end
    result[stack.pop()] += t - prev + 1; prev = t + 1
return result

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not subtracting child time from parent — exclusive time means time spent directly in the function, not in its children.

Stack Pattern