The stack simulation part clicked pretty fast for me.
Use a stack to track the currently executing function and the timestamp when it last resumed. When an 'end' event occurs, compute the function's exclusive time by subtracting the time spent in nested calls, then update the parent's exclusive time accordingly.
Pro tip: Clarify that timestamps are inclusive of both start and end moments, and that the CPU is single-threaded so events are strictly nested. This avoids off-by-one errors and shows attention to detail.
Parse each log string into function ID, event type, and timestamp. Ensure logs are processed in chronological order; if not already sorted, sort them by timestamp.
Create a stack to track active function calls and a map to accumulate exclusive time per function ID. The stack will store pairs of (function ID, start timestamp of current exclusive segment).
For a 'start' event: if the stack is not empty, add the time elapsed since the parent's last resume to the parent's exclusive time. Then push the new function with its start timestamp. For an 'end' event: pop the function, add the time from its start to the current timestamp (inclusive) to its exclusive time, and if the stack is not empty, update the parent's start timestamp to current timestamp + 1.
Account for the fact that both start and end timestamps are inclusive. When a function ends, its exclusive time includes the end timestamp, so duration = end - start + 1. When resuming a parent, its next segment starts at end + 1.
After processing all logs, return the map of function IDs to their exclusive execution times. Ensure all functions that started also ended (valid input).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.