The tricky part isn't the stack mechanics, it's remembering to handle the timestamp math correctly when a function resumes after a nested call returns.
Use a stack to track the currently executing function and a timestamp of when it last started or resumed. When a function ends, compute its exclusive time by subtracting the time spent in nested calls, and update the parent's accumulated time accordingly.
Pro tip: Clarify the log format and timestamp semantics upfront (e.g., whether end timestamps are inclusive) to avoid off-by-one errors, and mention that the stack approach naturally handles nested calls.
Parse each log entry into function ID, event type (start/end), and timestamp. Initialize a stack to track active functions and a map to store exclusive times.
On a start event, if the stack is not empty, add the time elapsed since the last event to the exclusive time of the function at the top of the stack. Then push the new function ID onto the stack and update the last timestamp.
On an end event, pop the function ID from the stack, add the time elapsed since the last event (inclusive of the end timestamp) to its exclusive time, and update the last timestamp to the end timestamp + 1.
Ensure that time spent in nested functions is correctly subtracted from the parent's exclusive time by updating the parent's time when a child starts or ends.
After processing all logs, return the map of function IDs to their exclusive execution times.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.