Per-Function Self Time from a Call Trace
Stacks & QueuesAuto-graded · 23 test casesLast updated
Sweep a single-threaded call trace with a stack to total each function's self time under half-open intervals, with recursion, strict validation, and name-sorted output.
Per-Function Self Time from a Call Trace
You are given a log of calls made by a single thread. Compute how much time each function spent running itself, meaning time during which it was the innermost active call and not waiting on a function it called.
Input format
trace is a list of events. Each event is a list of exactly three fields:
[name, action, time]
nameis a nonempty string naming a function.actionis exactly"start"or"end".timeis a nonnegative integer.
Events appear in nondecreasing order of time.
Rules
- A
"start"event begins a new call, which becomes the innermost active call. - An
"end"event finishes the innermost active call, and itsnamemust match that call. Recursion is permitted, so the same name may appear several times in the active chain. - Time is continuous and every interval is half-open. Between two consecutive events at times
aandb, the span[a, b)of lengthb - abelongs entirely to the innermost active call at that moment. If no call is active, that span belongs to no one. - Events with equal timestamps have no time between them and are applied in list order.
- For example, if
Astarts at 2, callsBat 5,Bends at 8, andAends at 10, thenBgets 3 andAgets(5 - 2) + (10 - 8) = 5. - Add up the self time across all calls of the same name, including recursive calls and calls from different callers.
Output
Return a list of [name, self_time] records, one for each distinct function name that appears in the trace (even if its self time is 0), sorted by name in ascending lexicographic order. An empty trace returns [].
Invalid traces
Raise ValueError if any of the following holds:
- an event is not a list of exactly three fields;
nameis not a nonempty string;actionis neither"start"nor"end";timeis not an integer, is a Boolean, or is negative;- a
timeis smaller than the previous event'stime; - an
"end"arrives when no call is active, or its name differs from the innermost active call; - the trace finishes while some call is still active.
Do not modify the input.
Constraints
0 <= len(trace) <= 500_0000 <= time <= 10**18- The trace is expected to start and finish with no active calls.
- Output is a list of
[str, int]pairs.
Examples
Example 1
Input: self_time_per_function([['main', 'start', 0], ['work', 'start', 2], ['work', 'end', 7], ['main', 'end', 10]])
Output: [['main', 5], ['work', 5]]
Example 2
Input: self_time_per_function([['main', 'start', 0], ['child', 'start', 2], ['child', 'end', 8], ['main', 'end', 10]])
Output: [['child', 6], ['main', 4]]
Example 3
Input: self_time_per_function([['f', 'start', 2], ['f', 'start', 4], ['f', 'end', 6], ['f', 'end', 9]])
Output: [['f', 7]]
Hints
Hint 1
Between two consecutive events exactly one call is running: the one on top of the stack, or nobody if the stack is empty.
Hint 2
For each event, first add the elapsed time since the previous event to the function currently on top of the stack, and only then push or pop.
Hint 3
Keep totals in a dictionary keyed by name so recursion and repeated calls merge automatically; register a name on its start so zero-time functions still appear. Check the Boolean-is-an-int trap when validating times.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the trace as a sweep over time with a call stack. The events split the timeline into consecutive half-open spans [t_i, t_{i+1}). Nothing changes inside a span, so exactly one function is running during it: the one on top of the stack (or nobody, if the stack is empty).
Keep two pieces of state:
stack: the chain of active calls, with the innermost on top.last_time: the timestamp of the previous event.
For each event at time t:
- Validate the event's shape, name, action, and time, and check that
tis not below the previous time. - Charge first: if the stack is nonempty, add
t - last_timeto the total of the function on top. - Then apply the event: on
"start", push the name and make sure it has an entry in the totals (starting at 0); on"end", check that the stack is nonempty and its top matches the name, then pop. - Set
last_time = t.
After the loop, the stack must be empty, otherwise raise ValueError. Return the totals sorted by name.
Why it is correct
The stack does not change within a span, so the stack state just before the event at the span's end is the state that held for the entire span. Charging the span to that top function, before applying the event, assigns every unit of running time to exactly the function that was executing. Gaps with an empty stack are never charged. Because only the top frame is ever charged, recursive frames of the same name never double-count, and aggregating by name merges all calls. Equal timestamps give spans of length 0, so list order is respected naturally. Since starts and ends are instants, no +1 adjustment is needed.
Validation happens before any state change for each event, and any failure raises, so partial results are never returned. The bool check must come before the int check because True is an instance of int in Python.
Complexity
- Time: O(n + k log k), where n is the number of events and k is the number of distinct names (the sort).
- Space: O(n) for the stack in the worst case (deep recursion) plus O(k) for the totals.
Reference solution
from typing import List
def self_time_per_function(trace: List[List[object]]) -> List[List[object]]:
totals = {}
stack = []
last_time = 0
seen_any = False
for event in trace:
if not isinstance(event, list) or len(event) != 3:
raise ValueError("Each event must be a list of three fields")
name, action, time = event
if not isinstance(name, str) or not name:
raise ValueError("Function name must be a nonempty string")
if action not in ("start", "end"):
raise ValueError("Invalid action")
if isinstance(time, bool) or not isinstance(time, int) or time < 0:
raise ValueError("Time must be a nonnegative integer")
if seen_any and time < last_time:
raise ValueError("Times must be nondecreasing")
# Charge the elapsed span to whoever is currently innermost.
if stack:
top = stack[-1]
totals[top] = totals.get(top, 0) + (time - last_time)
if action == "start":
stack.append(name)
totals.setdefault(name, 0)
else:
if not stack or stack[-1] != name:
raise ValueError("End does not match the active call")
stack.pop()
last_time = time
seen_any = True
if stack:
raise ValueError("Trace ended with active calls")
return [[name, totals[name]] for name in sorted(totals)]