My first instinct was to just iterate through logs and subtract child durations, but that falls apart fast with deeply nested calls.
Use a stack to track the currently executing function and its start time. When a new function starts, add the elapsed time since the last start to the exclusive time of the function on top of the stack, then push the new function. When a function ends, add the elapsed time including the current timestamp to its exclusive time, pop it, and update the start time for the next function on the stack.
Pro tip: Clarify whether the timestamps are inclusive or exclusive and handle the end timestamp carefully; off-by-one errors are common. Also, discuss how you would handle edge cases like nested calls and multiple calls to the same function.
Extract the function ID, start/end indicator, and timestamp from each log entry. Ensure you understand the format and any constraints.
Create an array to store exclusive times for each function (indexed by ID) and a stack to keep track of the call stack. The stack will store pairs of (function ID, start time).
For a start event: if the stack is not empty, add the time elapsed since the top's start time to the top function's exclusive time. Then push the new function with its start time. For an end event: add the time elapsed since the top's start time (including the current timestamp) to the top function's exclusive time, then pop the stack.
When a function ends, the time from its start to the end timestamp is exclusive to it, but if there were nested calls, those were already subtracted when the nested calls ended. After popping, update the start time of the new top function to the current timestamp + 1 to avoid double-counting.
After processing all logs, return the array of exclusive times for each function from 0 to n-1.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.