Stack-based solution is the right move here.
Use a stack to track the currently executing function and its start time. When a function starts, push it onto the stack; when it ends, pop it and add the elapsed time to its exclusive time, then adjust the parent's start time to account for the nested call. This ensures exclusive time excludes nested calls.
Pro tip: Clarify whether timestamps are inclusive or exclusive, as this affects the off-by-one calculation. Also, mention that the stack approach naturally handles arbitrary nesting depth and runs in O(n) time.
Parse each log entry into function ID, event type (start/end), and timestamp. Initialize an array of size n to store exclusive times and an empty stack to track active functions.
When encountering a start event, if the stack is not empty, add the time elapsed since the parent's start to the parent's exclusive time (to account for time before the child started). Then push the new function onto the stack with its start timestamp.
When encountering an end event, pop the function from the stack, compute its exclusive time by adding the duration from its start to the current timestamp (inclusive), and then update the parent's start time to the current timestamp + 1 (if timestamps are inclusive) to avoid double-counting.
Adjust calculations based on whether timestamps are inclusive or exclusive. For inclusive timestamps, duration = end - start + 1; for exclusive, duration = end - start. Ensure consistency throughout.
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.