The stack approach clicked pretty fast but I kept second-guessing the timestamp math.
Use a stack to track the call hierarchy and compute exclusive times by subtracting child durations from parent durations. Process logs in chronological order, and when a function ends, calculate its exclusive time as (end - start + 1) minus the sum of its children's exclusive times.
Pro tip: Clarify whether timestamps are inclusive or exclusive and whether they represent discrete time units (e.g., milliseconds) to avoid off-by-one errors. Also, mention that the stack approach naturally handles nested calls and is O(n) time and space.
Parse each log entry into function ID, event type (start/end), and timestamp. Ensure logs are sorted by timestamp; if not, sort them first.
Create an array to store exclusive times for each function (size n). Use a stack to keep track of currently executing functions and their start times.
Iterate through logs: on 'start', push function ID and timestamp onto stack. On 'end', pop the function, compute its exclusive time as (end - start + 1) minus the sum of exclusive times of its children (tracked separately), and add to the result array.
Maintain a separate stack or variable to accumulate child exclusive times for the current parent. When a child ends, add its exclusive time to the parent's child sum.
After processing all logs, return the array of exclusive times for each function.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.