Exclusive Time of Functions (LeetCode 636): Solution and Explanation

Medium
Array
Stack

Replay start and end logs of a single-threaded program and report how long each function ran on its own, not counting the functions it called. For logs 0:start:0, 1:start:2, 1:end:5, 0:end:6 the answer is [3,4].

Intuition

On a single thread, the function that is actually running is always the one most recently started that has not ended yet. That is exactly the top of a call stack.

So every stretch of time between two consecutive logs belongs entirely to whichever function is on top during that stretch. You never need to look at individual time units, only at the gaps.

The only subtle part is the units. A start at t begins at the start of unit t, while an end at t finishes at the end of unit t. Keep a pointer prev to the first unit nobody has been charged for yet, and both cases become one subtraction.

Approach: Call stack with a prev pointer

  1. Create res of size n filled with 0, an empty stack, and prev = 0.
  2. Split each log into id, kind and timestamp t.
  3. On start: if the stack is not empty, add t - prev to the function on top (it is paused). Push the new id and set prev = t.
  4. On end: pop the id and add t - prev + 1 to it, because unit t is included. Set prev = t + 1.
  5. Return res.

Step-by-step example

n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]
  1. 0:start:0: the stack is empty. Push 0, prev = 0.
  2. 1:start:2: function 0 ran during units 0 and 1, so res[0] += 2 - 0 = 2. Push 1, prev = 2.
  3. 1:end:5: pop 1 and add 5 - 2 + 1 = 4, so res[1] = 4. prev = 6, and function 0 resumes.
  4. 0:end:6: pop 0 and add 6 - 6 + 1 = 1, so res[0] = 3. prev = 7.
  5. The answer is [3,4].

Code: Python, Java, C++

1class Solution:
2    def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
3        res = [0] * n
4        stack = []
5        prev = 0
6        for entry in logs:
7            fid, kind, t = entry.split(':')
8            fid, t = int(fid), int(t)
9            if kind == 'start':
10                if stack:
11                    res[stack[-1]] += t - prev
12                stack.append(fid)
13                prev = t
14            else:
15                res[stack.pop()] += t - prev + 1
16                prev = t + 1
17        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(L)

Each of the L logs is parsed once and causes one push or one pop.

Space

O(L)

In the worst case every start is nested inside the previous one, so the stack holds L/2 ids. The output array is O(n).

Other approaches

Stack of (id, start time) with child time subtracted (time O(L), space O(L))

Push the id and its start time. When a function ends, its total duration is end - start + 1. Add that to its result, and subtract the same duration from the parent on the stack, because the parent did not run during it.

Simulate every time unit (time O(T), space O(L))

Walk the timeline one unit at a time and give each unit to the function on top. Correct, but timestamps go up to 10^9, so it is far too slow.

Common mistakes

  • Treating the end timestamp as exclusive. An end at t includes unit t, so the duration is t - prev + 1 and the next unit starts at t + 1.
  • Forgetting to charge the paused function when a new one starts. Its running time since prev would be lost.
  • Comparing "start" with == on Java strings. Use equals, or compare the first character.
  • Assuming a function cannot appear twice on the stack. Recursive calls push the same id again, and both copies must be charged to the same res entry.

Frequently asked questions

Why is the end time handled with +1 but the start time is not?

A start at t means the function begins at the beginning of unit t, so the previous owner ran up to but not including t. An end at t means the function used all of unit t, so its last unit is t and the next owner begins at t + 1.

What happens with recursion?

Nothing special. A recursive call pushes the same id again. Time is charged to whichever copy is on top, and all copies add into the same res entry, which is what the problem asks for.

Do I need to store start times on the stack?

Not with the prev pointer approach. prev already marks where the current owner's time began, so the stack only needs ids.