Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created November 19, 2023 21:47
Show Gist options
  • Select an option

  • Save optimistiks/1375b557c6edd8b0f3ec1867d0f3cbbd to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/1375b557c6edd8b0f3ec1867d0f3cbbd to your computer and use it in GitHub Desktop.
We are given an integer number, n, representing the number of functions running in a single-threaded CPU, and an execution log, which is essentially a list of strings. Each string has the format {function id}:{"start" | "end"}:{timestamp}, indicating that the function with function id either started or stopped execution at the time identified by…
export function exclusiveTime(n, events) {
const result = Array(n).fill(0);
const stack = [];
for (const event of events) {
const [id, action, time] = event.split(":");
if (action === "start") {
stack.push([id, action, time]);
}
if (action === "end") {
// calculate total execution time for the function we are ending
const [prevId, prevAction, prevTime] = stack.pop();
const total = time - prevTime + 1;
// add it to the result of this function
result[id] += total;
// if it's a nested function we are ending,
// we need to subtract it's execution time
// from the parent function execution time
if (stack.length > 0) {
result[stack[stack.length - 1][0]] -= total;
}
}
}
return result;
}
// tc: O(n)
// sc: O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment