Problem Description
Given a list of logs representing the start and end times of function calls on a single-threaded CPU, compute the exclusive time spent in each function. The exclusive time for a function is the sum of execution times for all instances of that function, excluding the time spent executing other functions called within it.
Key Insights
- Use a stack to simulate function calls; the top of the stack represents the currently executing function.
- When a function starts while another is running, update the exclusive time of the currently running function.
- For an "end" log, add the elapsed time (including the current timestamp) to the function on top of the stack.
- Keep track of the previous timestamp to calculate elapsed durations correctly.
Space and Time Complexity
Time Complexity: O(n) where n is the number of log entries. Space Complexity: O(n) in the worst-case scenario due to the stack.
Solution
We use a stack to track the active functions. As we iterate through each log:
- For a "start" log, if there is a function currently executing (top of the stack), update its exclusive time with the time elapsed since the last timestamp.
- Then push the new function onto the stack and update the previous timestamp.
- For an "end" log, pop the completed function from the stack and update its exclusive time by adding the elapsed time plus one (to account for the inclusive end timestamp). Then update the previous timestamp to one more than the current timestamp. This approach efficiently tracks the execution time intervals for each function.