Given n functions and a list of logs (each log is "function_id:start/end:timestamp"), compute the exclusive execution time of each function.
Input: n=2, logs=["0:start:0","1:start:2","1:end:5","0:end:6"] → Output: [3,4]Input: n=1, logs=["0:start:0","0:start:2","0:end:5","0:end:6"] → Output: [8]
Use a stack to track the currently running function. On each log, if start: push function id and record time. If end: pop and add duration. Subtract paused time for nested functions.
- Parse each log into (id, type, time).
- Maintain a stack of function IDs and a prevTime variable.
- On start: if stack non-empty, add (time - prevTime) to top function. Push id, prevTime = time.
- On end: add (time - prevTime + 1) to current function. Pop stack, prevTime = time + 1.
import java.util.*;
class Solution {
public int[] exclusiveTime(int n, List<String> logs) {
int[] result = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
int prevTime = 0;
for (String log : logs) {
String[] parts = log.split(":");
int id = Integer.parseInt(parts[0]);
int time = Integer.parseInt(parts[2]);
boolean isStart = parts[1].equals("start");
if (isStart) {
if (!stack.isEmpty()) result[stack.peek()] += time - prevTime;
stack.push(id);
prevTime = time;
} else {
result[stack.pop()] += time - prevTime + 1;
prevTime = time + 1;
}
}
return result;
}
}
- Time Complexity: O(N) where N = number of log entries
- Space Complexity: O(N) stack