Compute exclusive CPU time from nested logs
Company: Decagon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates the ability to interpret execution logs and compute exclusive CPU time, testing skills in parsing structured logs, reasoning about nested execution intervals, and precise time accounting.
Constraints
- 1 <= n <= 10^5
- 1 <= logs.length <= 10^5
- 0 <= functionId < n
- 0 <= timestamp <= 10^9
- Timestamps are non-decreasing across logs
- Logs are valid and properly nested
Examples
Input: (2, ["0:start:0", "1:start:2", "1:end:5", "0:end:6"])
Expected Output: [3, 4]
Explanation: Function 0 runs at times 0, 1, and 6 for a total of 3. Function 1 runs at times 2 through 5 inclusive for a total of 4.
Input: (1, ["0:start:0", "0:end:0"])
Expected Output: [1]
Explanation: The function starts and ends at timestamp 0, which counts as 1 unit because end timestamps are inclusive.
Input: (2, ["0:start:0", "0:end:2", "1:start:3", "1:end:4"])
Expected Output: [3, 2]
Explanation: Function 0 runs from 0 through 2 for 3 units. Function 1 runs from 3 through 4 for 2 units.
Input: (1, ["0:start:0", "0:start:2", "0:end:3", "0:end:4"])
Expected Output: [5]
Explanation: Function 0 calls itself. Across both invocations, function 0 is executing during every timestamp from 0 through 4, for 5 total units.
Input: (3, ["0:start:0", "1:start:1", "1:end:2", "2:start:3", "2:end:3", "0:end:4"])
Expected Output: [2, 2, 1]
Explanation: Function 0 runs at timestamps 0 and 4. Function 1 runs at timestamps 1 and 2. Function 2 runs only at timestamp 3.
Hints
- Because function calls are properly nested, consider using a stack to track which function is currently running.
- Keep track of the previous timestamp boundary. When a new function starts, the function on top of the stack has been running until just before that timestamp. When a function ends, remember that the end timestamp is inclusive.