Leetcode 636. Exclusive Time of Functions
24 December 2025
•3 min read
Description
You have a single-threaded CPU that executes a program with n functions, where each function has a unique ID from 0 to n-1.
The execution follows a call stack pattern:
When a function starts, its ID is pushed onto the stack
When a function ends, its ID is popped from the stack
The function at the top of the stack is the one currently executing
You're given a list of logs where each log entry is formatted as: "{function_id}:{"start" | "end"}:{timestamp}"
Code Example
Here's a Java code:
java
class Solution {
public int[] exclusiveTime(int n, List<String> logs) {
int[] ans = new int[n];
Stack<Integer> stack = new Stack<>();
int lastTime = 0;
for(String l : logs) {
String[] spl = l.split(":");
if(spl[1].equals("start")){
if(!stack.isEmpty()) {
int lastOne = stack.peek();
ans[lastOne] += Integer.parseInt(spl[2]) - lastTime;
}
lastTime = Integer.parseInt(spl[2]);
stack.push(Integer.parseInt(spl[0]));
}else{
int lastOne = stack.pop();
ans[lastOne] += Integer.parseInt(spl[2]) - lastTime +1;
lastTime = Integer.parseInt(spl[2]) + 1;
}
}
return ans;
}
}