Self-Time Accounting for Nested Call Traces
Stacks & QueuesAuto-graded · 18 test casesLast updated
Use a stack to turn start/end trace records of nested calls on one CPU into each function's self-time, with inclusive end timestamps.
Self-Time Accounting for Nested Call Traces
A single-core processor runs n functions, numbered 0 to n - 1. Only one function executes at any moment. A trace records what happened as a list of strings, each shaped like "id:kind:time":
idis the function's number.kindis eitherstartorend.timeis an integer timestamp.
A running function may call another function (including itself). The caller is paused while the callee runs and resumes once the callee ends. Calls nest properly, so the most recently started call that has not yet ended is always the one to end next.
Time-unit convention
Time is divided into whole units, where unit t covers the interval from the start of t to the start of t + 1.
- A
startrecord at timetmeans the function begins at the beginning of unitt, so it occupies unitt. - An
endrecord at timetmeans the function finishes at the end of unitt, so it also occupies unitt.
A call that starts and ends at the same timestamp t therefore uses exactly one unit.
Task
Return a list of length n where entry i is the self-time of function i: the total number of time units during which function i was the one actually executing. Time spent inside functions it called does not count toward it. If a function is called several times, or calls itself recursively, add up the self-time of all its calls.
Function
Implement self_times(n, records), which takes the number of functions n and the list of trace strings records, and returns the list of self-times indexed by function number.
Constraints
1 <= n <= 1001 <= len(records) <= 500- Timestamps never decrease from one record to the next.
- The trace is valid: every call ends after any call it made has ended, and every
starthas a matchingend. - Every
idis in the range0ton - 1.
Examples
Example 1
Input: self_times(2, ['0:start:0', '1:start:2', '1:end:5', '0:end:6'])
Output: [3, 4]
Example 2
Input: self_times(1, ['0:start:0', '0:start:1', '0:end:1', '0:end:2'])
Output: [3]
Example 3
Input: self_times(3, ['0:start:0', '1:start:0', '1:end:0', '2:start:1', '2:end:3', '0:end:3'])
Output: [0, 1, 3]
Hints
Hint 1
Because calls nest, the function that is currently executing is always the most recently started call that has not yet ended. Which data structure models that?
Hint 2
Keep a marker for the first time unit that has not yet been credited to anyone. On each record, give the elapsed units since the marker to the function on top of the stack, then update the marker.
Hint 3
Starts and ends differ in how they treat the timestamp. A start at t has not used unit t for the previous function, but an end at t does use unit t for the ending function, so the marker moves to t + 1 after an end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since calls nest, the function using the CPU is always the most recently started call that has not yet ended. That is the top of a stack.
We scan the records in order and maintain:
active: a stack of function ids for calls that are in progress.marker: the first time unit that has not yet been credited to any function.totals: the answer array.
For each record with timestamp t:
start: the function currently on top (if any) has been running over unitsmarker .. t - 1, which ist - markerunits. Credit them to it. Push the new function and setmarker = t.end: the function on top has been running over unitsmarker .. t, inclusive, which ist - marker + 1units. Pop it, credit it, and setmarker = t + 1, since the caller (if any) resumes at unitt + 1.
Why it is correct
Before each record, every unit earlier than marker has been credited to exactly one function, and the top of the stack has been running without interruption since marker. Each record's update preserves this: a start closes the top's current run just before t, and an end closes the ending function's run through t inclusive. The trace is valid, so each end matches the top of the stack and the right function is credited. Callee time is never added to the caller because the marker moves past it. Recursion works naturally because the stack stores ids, so the same id can appear several times and all its frames add to the same total. Back-to-back events (an end at t followed by a start at t + 1) credit zero units, which is correct because there is no gap.
Complexity
- Time: O(L), where L is the number of records (each is parsed and processed in constant time).
- Space: O(n + D), where D is the maximum nesting depth.
Reference solution
from typing import List
def self_times(n: int, records: List[str]) -> List[int]:
totals = [0] * n
active = [] # ids of calls that have started but not ended
marker = 0 # first time unit not yet credited to any function
for rec in records:
fid_text, kind, time_text = rec.split(":")
fid = int(fid_text)
t = int(time_text)
if kind == "start":
if active:
totals[active[-1]] += t - marker
active.append(fid)
marker = t
else:
top = active.pop()
totals[top] += t - marker + 1
marker = t + 1
return totals