Created
November 19, 2023 21:47
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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