Exclusive Time of Functions

A single-threaded CPU runs a program with `n` functions, each with an id from `0` to `n - 1`. Function calls use a call stack: a call pushes the id, and when a function ends its id is popped. You are given `logs`, where each entry is `"{id}:start:{timestamp}"` or `"{id}:end:{timestamp}"`. A start log means the function began at the beginning of that timestamp, and an end log means it finished at the end of that timestamp. A function may be called several times, including recursively. The exclusive time of a function is the total time it spent running, not counting time spent in functions it called. Return an array where entry `i` is the exclusive time of function `i`.

30:00

Exclusive Time of Functions
medium
Free written solution
Topics
Companies

A single-threaded CPU runs a program with n functions, each with an id from 0 to n - 1. Function calls use a call stack: a call pushes the id, and when a function ends its id is popped. You are given logs, where each entry is "{id}:start:{timestamp}" or "{id}:end:{timestamp}". A start log means the function began at the beginning of that timestamp, and an end log means it finished at the end of that timestamp. A function may be called several times, including recursively. The exclusive time of a function is the total time it spent running, not counting time spent in functions it called. Return an array where entry i is the exclusive time of function i.

Example 1:
Input: {"n":2,"logs":["0:start:0","1:start:2","1:end:5","0:end:6"]}
Output: [3,4]
Constraints:
  • 1≤n≤1001 \leq n \leq 100

  • 1≤logs.length≤5001 \leq \text{logs.length} \leq 500

  • 0≤function_id<n0 \leq \text{function\_id} < n

  • 0≤timestamp≤1090 \leq \text{timestamp} \leq 10^9

  • No two start events or two end events happen at the same timestamp.

  • Each function has an end log for each start log.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":2,"logs":["0:start:0","1:start:2","1:end:5","0:end:6"]}
0:▶:0
1:▶:2
1:■:5
0:■:6

CPU timeline (each block = time charged to that function)

prev = 0

f0
f1

0

1

2

3

4

5

6

7

| prev: first unit not yet charged

2 functions, 4 logs. Only the function on top of the call stack is running, so every time unit is charged to whoever is on top.

call stack

empty

exclusive time res[]

f0

0

f1

0

Variables
VariableValue
prev0
stack[]
res[0,0]
DepthFunction Call
Stack empty
0/10