636. Exclusive Time of Functions
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method: Using a Stack
The problem asks for the exclusive execution time of several functions running on a single-threaded CPU. The function calls follow a stack-based model (Last-In, First-Out), which is a strong hint to use a stack data structure to solve this problem.
Solution
Exclusive Time of Functions in Python
class Solution:
def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
res = [0] * n
stack = [] # Stores function IDs
prev_time = 0
for log in logs:
# Parse the log string
parts = log.split(':')
func_id = int(parts[0])
event_type = parts[1]
timestamp = int(parts[2])
# If there's a function on the call stack, it has been running until now.
if stack:
res[stack[-1]] += timestamp - prev_time
# Update prev_time to the current timestamp.
prev_time = timestamp
if event_type == 'start':
# A new function starts, push it onto the stack.
stack.append(func_id)
else: # event_type == 'end'
# The function at the top of the stack ends.
# It ran for the entire duration of the current timestamp, so add 1.
res[stack.pop()] += 1
# The next time interval starts at the next integer time.
prev_time += 1
return res
Exclusive Time of Functions in Java
class Solution {
public int[] exclusiveTime(int n, List<String> logs) {
int[] res = new int[n];
Stack<Integer> stack = new Stack<>(); // Stores function IDs
int prevTime = 0;
for (String log : logs) {
// Parse the log string
String[] parts = log.split(":");
int id = Integer.parseInt(parts[0]);
String type = parts[1];
int timestamp = Integer.parseInt(parts[2]);
// If there's a function on the call stack, it has been running until now.
if (!stack.isEmpty()) {
res[stack.peek()] += timestamp - prevTime;
}
// Update prevTime to the current timestamp.
prevTime = timestamp;
if (type.equals("start")) {
// A new function starts, push it onto the stack.
stack.push(id);
} else { // type.equals("end")
// The function at the top of the stack ends.
// It ran for the entire duration of the current timestamp, so add 1.
res[stack.peek()]++;
stack.pop();
// The next time interval starts at the next integer time.
prevTime++;
}
}
return res;
}
}
Exclusive Time of Functions in C++
class Solution {
public:
vector<int> exclusiveTime(int n, vector<string>& logs) {
vector<int> res(n, 0);
stack<int> st; // Stores function IDs
int prev_time = 0;
for (const string& log : logs) {
// Parse the log string
size_t first_colon = log.find(':');
size_t second_colon = log.find(':', first_colon + 1);
int id = stoi(log.substr(0, first_colon));
string type = log.substr(first_colon + 1, second_colon - first_colon - 1);
int timestamp = stoi(log.substr(second_colon + 1));
// If there's a function on the call stack, it has been running until now.
if (!st.empty()) {
res[st.top()] += timestamp - prev_time;
}
// Update prev_time to the current timestamp.
prev_time = timestamp;
if (type == "start") {
// A new function starts, push it onto the stack.
st.push(id);
} else { // type == "end"
// The function at the top of the stack ends.
// It ran for the entire duration of the current timestamp, so add 1.
res[st.top()]++;
st.pop();
// The next time interval starts at the next integer time.
prev_time++;
}
}
return res;
}
};
Exclusive Time of Functions in TypeScript
function exclusiveTime(n: number, logs: string[]): number[] {
const res: number[] = new Array(n).fill(0);
const stack: number[] = []; // Stores function IDs
let prevTime = 0;
for (const log of logs) {
// Parse the log string
const parts = log.split(':');
const id = parseInt(parts[0]);
const type = parts[1];
const timestamp = parseInt(parts[2]);
// If there's a function on the call stack, it has been running until now.
if (stack.length > 0) {
const runningFuncId = stack[stack.length - 1];
res[runningFuncId] += timestamp - prevTime;
}
// Update prevTime to the current timestamp.
prevTime = timestamp;
if (type === 'start') {
// A new function starts, push it onto the stack.
stack.push(id);
} else { // type === 'end'
// The function at the top of the stack ends.
// It ran for the entire duration of the current timestamp, so add 1.
const finishedFuncId = stack.pop()!;
res[finishedFuncId]++;
// The next time interval starts at the next integer time.
prevTime++;
}
}
return res;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.