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 functions, with ids 0 to n - 1. Only one function runs at a time, and a function can call other functions, including itself. Each call writes a log when it starts and when it ends, as "id:start:t" or "id:end:t".

Time is counted in whole units. A start at t means the function begins at the beginning of time unit t, and an end at t means it finishes at the end of unit t. A function's exclusive time is the number of units it spent running itself, not counting time spent in functions it called.

Given n and the logs in time order, return an array whose position i holds 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]
Explanation: function 0 runs units 0, 1 and 6; function 1 runs units 2 to 5.
Example 2
Input: n = 1, logs = ["0:start:0", "0:start:2", "0:end:5", "0:start:6", "0:end:6", "0:end:7"]
Output: [8]
Explanation: function 0 calls itself twice; all 8 units, 0 to 7, belong to it.
Solution

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.

Example 1 on a timeline of units 0 to 6. 0:start:0 is at the left edge of unit 0 and 1:start:2 at the left edge of unit 2. 1:end:5 is at the right edge of unit 5, so the next unit is 6, and 0:end:6 is at the right edge of unit 6. Function 0 runs units 0, 1 and 6, function 1 runs units 2 to 5, and the stack holds [0], then [0, 1], then [0].

The two start logs, 0:start:0 and 1:start:2, sit at the left edges of units 0 and 2. The two end logs sit at right edges: 1:end:5 covers unit 5, as the label "covers unit 5" under it says, so unit 6 is the next one free. Counting boxes gives function 0 units 0, 1 and 6, three in all, and function 1 units 2 to 5, four. That is the output [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 ArrayDeque works as a stack: push puts an id on top, peek reads the top id, and pop removes and returns it. A start log pushes its id. An end log pops, because the function that ends is always the one on top: a function cannot finish while a function it called is still running.

Counting the units between two logs

How many units does the top function get? Keep prev, the first time unit not yet given to any function. A start at t means the function on top ran units prev to t - 1, which is t - prev units. The new function begins in unit t, so prev becomes t.

An end at t includes unit t itself, so the ending function ran t - prev + 1 units. Unit t is then used up, and prev becomes t + 1. In Example 1, 1:start:2 gives function 0 2 - 0 = 2 units. 1:end:5 gives function 1 5 - 2 + 1 = 4 units and moves prev to 6. Then 0:end:6 gives function 0 6 - 6 + 1 = 1 more unit, three in all.

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 works in these steps:

  1. First, create the result array time, with one count per function, and an empty ArrayDeque named running for the call stack. Set prev to 0, since no unit has been given out yet.
  2. Go through the logs in order. Split each one at the colons with log.split(":"), which gives the id, the word start or end, and the timestamp t.
  3. On a start, if running is not empty, add t - prev to the count of the function on top, found with running.peek(). Then push the new id and set prev to t.
  4. On an end, pop the top id from running, add t - prev + 1 to its count, and set prev to t + 1.
  5. When all the logs are read, return time.

The main method runs both examples, a function 0 that calls two functions one after the other, and a case where function 0 has no logs and function 1 starts and ends in the same unit.

Java
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:

Output
[3, 4]
[8]
[2, 1, 2]
[0, 1]

[3, 4] and [8] match Examples 1 and 2. On the third line, function 0 hands unit 1 to function 1 and units 2 and 3 to function 2, and keeps units 0 and 4, so the result is [2, 1, 2]. Here 1:end:1 sets prev to 2, and 2:start:2 then gives function 0 2 - 2 = 0 units, which is right: no time passed between the two calls.

The last line, [0, 1], shows two small cases at once. Function 0 never ran, so its count stays 0. Function 1 starts and ends at 3, and 3 - 3 + 1 gives it exactly one unit.

The + 1 on an end and prev = t + 1 after it are easy to get wrong. With prev = t after an end instead, Example 1 returns [4, 4]. After 1:end:5, prev stays at 5, so 0:end:6 gives function 0 6 - 5 + 1 = 2 units, counting unit 5 a second time.

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 time 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 the ArrayDeque takes constant time.
  • 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 time array of size n is the output.

A stack that keeps track of unfinished nested parts also solves Decode String, where the nested parts are brackets.