Compute exclusive execution time from logs
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of event log interpretation, nested call stack behavior, and exclusive time accounting for functions in a single-threaded execution model.
Constraints
- 1 <= n <= 10^5
- 1 <= len(logs) <= 2 * 10^5
- Each log has the form "<function_id>:<event>:<timestamp>"
- 0 <= timestamp
- Logs are in chronological order and form a valid properly nested call stack
Examples
Input: (2, ["0:start:0", "1:start:2", "1:end:5", "0:end:6"])
Expected Output: [3, 4]
Explanation: Function 0 runs from 0 to 1, function 1 runs from 2 to 5, and function 0 resumes at 6. So the exclusive times are 3 and 4.
Input: (1, ["0:start:0", "0:end:0"])
Expected Output: [1]
Explanation: A single function starts and ends at the same timestamp, so it executes for exactly one time unit.
Input: (1, ["0:start:0", "0:start:2", "0:end:5", "0:end:6"])
Expected Output: [7]
Explanation: The same function calls itself recursively. The outer call contributes 3 exclusive units and the inner call contributes 4, for a total of 7 for function 0.
Input: (3, ["0:start:0", "0:end:1", "1:start:2", "1:end:2", "2:start:3", "2:end:4"])
Expected Output: [2, 1, 2]
Explanation: There is no nesting here. Each function's exclusive time is simply its full runtime.
Input: (3, ["0:start:0", "1:start:1", "1:end:1", "2:start:2", "2:end:4", "0:end:5"])
Expected Output: [2, 1, 3]
Explanation: Function 0 runs at time 0 and again at time 5. Function 1 runs for 1 unit and function 2 runs from 2 to 4 for 3 units.
Solution
def solution(n, logs):
exclusive = [0] * n
stack = []
prev_time = 0
for log in logs:
fn_id_str, event, ts_str = log.split(":")
fn_id = int(fn_id_str)
ts = int(ts_str)
if event == "start":
if stack:
exclusive[stack[-1]] += ts - prev_time
stack.append(fn_id)
prev_time = ts
else:
exclusive[stack.pop()] += ts - prev_time + 1
prev_time = ts + 1
return exclusiveTime complexity: O(len(logs)). Space complexity: O(n + max_call_depth).
Hints
- Use a stack to track which function is currently running.
- Keep a previous timestamp pointer. When processing an end event at time t, remember that the function used the CPU through time t, so you should add one extra unit and move the pointer to t + 1.