Exclusive Time of Functions
Replay start and end logs on a call stack to find how many time units each function ran by itself.
A computer with one processor runs n"id:start:t""id:end:t"
Time is counted in whole units. A start at tttt
Given nii
Example 1
Output: [3, 4]
Explanation: function 0 runs units 0, 1 and 6; function 1 runs units 2 to 5.
Example 2
Output: [8]
Explanation: function 0 calls itself twice; all 8 units, 0 to 7, belong to it.
The Idea
Think of someone writing a report who keeps getting interrupted. A colleague asks a question, they answer it, and then they go back to the report. A fair timesheet shows the time spent on each task, not the whole stretch from opening the report to finishing it. Function calls work the same way: while function 1 runs, function 0 only waits for it, and that time belongs to function 1.
Now lay Example 1 out on a timeline. Function 0 starts at the beginning of unit 0. At the beginning of unit 2 it calls function 1, which runs until the end of unit 5. Then function 0 carries on and ends at the end of unit 6. Look at the picture below.
The two start logs, 0:start:01:start:21:end:5[3, 4]
A program, though, sees only the four logs, one at a time. So two questions come up. When a log arrives, which function was running just before it? And how many units did that function get since the previous log?
The row of boxes along the bottom, "stack [0]", then "stack [0, 1], 1 on top", then "stack [0]" again, answers the first one. The functions that have started but not ended are like a pile of plates: a new call goes on top, an end takes the top one off, and the one on top is the one running. A pile that you only change at the top is called a stack, and a program's pile of unfinished calls is its call stack.
The second question, how many units, is about the edges. Starts mark the left edge of a unit and ends mark the right edge. So remember the first unit that has not been given to anyone yet, and at every log, give the units from there up to the log to the function on top of the stack.
Solution Approach
Turning that idea into code means settling four things: whether to mark each time unit one by one, which function is running, how many units it gets between two logs, and what a function calling itself changes.
Marking every time unit
Why not simply fill in the timeline? An array with one cell per time unit could hold each unit's owner, and counting the cells at the end gives the answer. That is fine for Example 1, with its seven units. But the work grows with the last timestamp, not with the number of logs: two logs at 0 and 1,000,000 would mean a million cells. Giving out a whole stretch of units at each log takes one step per log instead.
Knowing which function is running
Which function owns the units just before a log? The one on top of the stack. Java's ArrayDequepushpeekpop
Counting the units between two logs
How many units does the top function get? Keep prevtprevt - 1t - prevtprevt
An end at ttt - prev + 1tprevt + 11:start:21:end:5prev0:end:6
The very first log finds the stack empty. Nothing ran before it, so there is nobody to give units to.
A function that calls itself
What if the same id is on the stack twice? In Example 2, function 0 calls itself, first for units 2 to 5 and then for unit 6. Each call is its own entry on the stack, but they all add into the same count for function 0. Every unit from 0 to 7 goes to some call of function 0, so the answer is [8]
Java Solution
The method exclusiveTime
- First, create the result array
, with one count per function, and an emptytime namedArrayDeque for the call stack. Setrunning to 0, since no unit has been given out yet.prev - Go through the logs in order. Split each one at the colons with
, which gives the id, the wordlog.split(":") orstart , and the timestampend .t - On a start, if
is not empty, addrunning to the count of the function on top, found witht - prev . Then push the new id and setrunning.peek() toprev .t - On an end, pop the top id from
, addrunning to its count, and sett - prev + 1 toprev .t + 1 - When all the logs are read, return
.time
The main
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
public class ExclusiveTimeOfFunctions {
public static int[] exclusiveTime(int n, List<String> logs) {
int[] time = new int[n];
Deque<Integer> running = new ArrayDeque<>(); // the call stack of function ids
int prev = 0; // first time unit not yet given out
for (String log : logs) {
String[] parts = log.split(":");
int id = Integer.parseInt(parts[0]);
int t = Integer.parseInt(parts[2]);
if (parts[1].equals("start")) {
if (!running.isEmpty()) {
time[running.peek()] += t - prev; // the caller ran up to unit t - 1
}
running.push(id);
prev = t;
} else {
time[running.pop()] += t - prev + 1; // an end includes unit t
prev = t + 1;
}
}
return time;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(exclusiveTime(2,
List.of("0:start:0", "1:start:2", "1:end:5", "0:end:6"))));
System.out.println(Arrays.toString(exclusiveTime(1,
List.of("0:start:0", "0:start:2", "0:end:5", "0:start:6", "0:end:6", "0:end:7"))));
System.out.println(Arrays.toString(exclusiveTime(3,
List.of("0:start:0", "1:start:1", "1:end:1", "2:start:2", "2:end:3", "0:end:4"))));
System.out.println(Arrays.toString(exclusiveTime(2,
List.of("1:start:3", "1:end:3"))));
}
}
Running it prints:
[3, 4]
[8]
[2, 1, 2]
[0, 1]
[3, 4][8][2, 1, 2]1:end:1prev2:start:2
The last line, [0, 1]
The + 1prev = t + 1prev = t[4, 4]1:end:5prev0:end:6
Complexity
Each log is read once and causes one push or one pop, so the work follows the number of logs, L.
- Time: O(n + L). Creating
fills n counts with 0. Each of the L logs is a short string, split and parsed in a few steps, and its push, peek or pop on thetime takes constant time.ArrayDeque - Space: O(L) besides the output. The stack is deepest when calls are nested inside each other and every start comes before any end. Then it holds L / 2 ids. The
array of size n is the output.time
A stack that keeps track of unfinished nested parts also solves