The Exclusive Time of Functions interview question asks you to calculate the total execution time for each function in a single-threaded CPU. You are given a list of logs, where each log contains a function ID, an action ("start" or "end"), and a timestamp. "Exclusive time" means the time spent only in that function, excluding time spent in any other functions it calls.
Companies like Uber, Microsoft, and Meta use this Stack interview pattern to see if you can model process execution. It mimics how profilers and operating systems track CPU usage. It tests your ability to handle nested events and manage "paused" state using a stack. It also checks for precision in calculating time intervals (handling the inclusive nature of timestamps).
This problem is a classic application of a Stack.
prev_time variable.prev_time to the function at the top of the stack.prev_time.prev_time (inclusive) to that function's total.prev_time to the next second.Logs: ["0:start:0", "1:start:2", "1:end:5", "0:end:6"]
0:start:0: Push 0. prev = 0.1:start:2: Stack has 0. 0 ran for 2-0 = 2 seconds. Push 1. prev = 2.1:end:5: Pop 1. 1 ran for 5-2 + 1 = 4 seconds. prev = 6.0:end:6: Pop 0. 0 ran for 6-6 + 1 = 1 more second.
Total: 0: 3s, 1: 4s.end:5 after start:2 is 4 seconds (2, 3, 4, 5), not 3.Draw a timeline on a piece of paper. Visualize how the "active" function changes and how the clock ticks. This makes it much easier to decide exactly when to update the prev_time pointer.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Validate Stack Sequences | Medium | Solve | |
| Buildings With an Ocean View | Medium | Solve | |
| Next Greater Element II | Medium | Solve | |
| Sum of Subarray Ranges | Medium | Solve | |
| Design a Stack With Increment Operation | Medium | Solve |