Exclusive Time of Functions solution explained

Exclusive Time of Functions gives you the start and end log lines of function calls on a single-threaded processor and asks how much time each function spent running itself, not counting the time its callees ran. Replay the log with a stack: the function on top of the stack is the one running, so each new event charges the time since the previous event to that function, then pushes or pops. Remember that an end timestamp includes its own time unit. It runs in O(m) time for m log lines.

By Published 7 min read

Restating the problem

A program with n functions, numbered 0 to n - 1, runs on one CPU thread. You receive its log as a list of strings in time order. Each string has the form "id:start:t" or "id:end:t". Time is counted in whole units: a function that starts at t begins at the start of unit t, and a function that ends at t keeps running until the end of unit t. When a function calls another, the caller pauses until the callee ends, and a function may call itself. Return a list where entry i is the number of units function i spent running its own code, summed over all of its calls.

n = 2
["0:start:0", "1:start:3", "1:end:5", "0:end:8"]
  ->  [6, 3]     function 0 runs units 0-2 and 6-8; function 1 runs 3-5

n = 1
["0:start:0", "0:start:1", "0:end:1", "0:end:3"]
  ->  [4]        the outer call gets units 0, 2 and 3; the recursive call gets unit 1

n = 3
["0:start:0", "0:end:1", "2:start:4", "1:start:5", "1:end:5", "2:end:7"]
  ->  [2, 1, 3]  units 2 and 3 are idle and belong to nobody
Logs made up for this page, with each function's exclusive time

What it tests

This is a stack simulation with an off-by-one trap built in. Interviewers want to see you model the call stack directly, find the rule for whose time is passing between two events, and handle the asymmetry between start and end timestamps without patching numbers until the example works. It also rewards parsing the log lines cleanly.

Slow but sure: count every time unit

First match each end with its start to get one interval per call. Then walk every time unit from zero to the last end. Among the calls whose interval covers that unit, the innermost one is running, and with proper nesting that is the one that started latest. Add one to its function. This is easy to trust, but it costs time proportional to the length of the timeline times the number of calls, so a single long-running call makes it very slow.

def exclusive_time_slow(n, logs):
    intervals, open_calls = [], []
    for entry in logs:
        fid, kind, t = entry.split(":")
        if kind == "start":
            open_calls.append((int(fid), int(t)))
        else:
            fid, start = open_calls.pop()
            intervals.append((start, int(t), fid))
    result = [0] * n
    last = max(end for _, end, _ in intervals)
    for unit in range(last + 1):
        running = [(s, f) for s, e, f in intervals if s <= unit <= e]
        if running:
            result[max(running)[1]] += 1     # latest start is innermost
    return result
Python: intervals first, then one unit at a time. A test reference only.

One pass with a call stack

Between two consecutive log events, exactly one thing is true: either the function on top of the stack is running, or the stack is empty and the CPU is idle. So you only need to know how much time has passed since the last event and whose it was. Keep a marker prev for the first time unit that nobody has been charged for yet.

  • Start at t: the function on top (if any) ran from prev up to but not including unit t, so charge it t - prev. Push the new id and set prev = t.
  • End at t: the function on top ran from prev through unit t inclusive, so charge it t - prev + 1. Pop it and set prev = t + 1, because unit t is used up.
def exclusive_time(n, logs):
    result = [0] * n
    stack = []
    prev = 0                      # first unit not yet charged to anyone
    for entry in logs:
        fid, kind, t = entry.split(":")
        fid, t = int(fid), int(t)
        if kind == "start":
            if stack:
                result[stack[-1]] += t - prev
            stack.append(fid)
            prev = t
        else:
            result[stack.pop()] += t - prev + 1
            prev = t + 1
    return result
Python: one pass over the log
function exclusiveTime(n, logs) {
  const result = new Array(n).fill(0);
  const stack = [];
  let prev = 0;
  for (const entry of logs) {
    const [idText, kind, timeText] = entry.split(":");
    const id = Number(idText);
    const t = Number(timeText);
    if (kind === "start") {
      if (stack.length) result[stack[stack.length - 1]] += t - prev;
      stack.push(id);
      prev = t;
    } else {
      result[stack.pop()] += t - prev + 1;
      prev = t + 1;
    }
  }
  return result;
}
JavaScript: the same replay

Idle gaps take care of themselves. After the last open call ends, the stack is empty, so the next start charges nobody, and prev jumps forward to the new start time.

Tracing the first example

n = 2, logs 0:start:0, 1:start:3, 1:end:5, 0:end:8
EventChargeStack afterprev after
0:start:0nobody (stack empty)00
1:start:3function 0 gets 3 - 0 = 30, 13
1:end:5function 1 gets 5 - 3 + 1 = 306
0:end:8function 0 gets 8 - 6 + 1 = 3(empty)9
n = 2, logs 0:start:0, 1:start:3, 1:end:5, 0:end:8. Scroll sideways on a small screen.

Complexity

m log lines, T the last timestamp
ApproachTimeExtra space
Unit-by-unit timelineO(T · m)O(m) for the intervals
Call stack replayO(m)O(m) for the stack, plus O(n) for the answer
m log lines, T the last timestamp. Scroll sideways on a small screen.

Inputs that catch bugs

  • A call that starts and ends in the same unit, like "1:start:5", "1:end:5": it gets 1, not 0.
  • Recursion, where the same id is on the stack twice: the result simply adds up both calls.
  • Idle gaps between top-level calls: nobody gets those units.
  • Deep nesting with a callee ending one unit before the caller resumes, so the caller's next charge starts at t + 1.
  • Function ids with more than one digit, like "12:start:40": split on the colon rather than reading single characters.

Common mistakes

  • Using t - prev on an end event, which loses the unit at t for every call.
  • Setting prev = t after an end instead of t + 1, which charges unit t twice.
  • Charging the new function on a start instead of the one that was running before it.
  • Storing exclusive time per call instead of per function id, so recursion overwrites earlier totals.
  • Subtracting each callee's total from its caller afterwards; possible, but easy to get wrong with nested and recursive calls.

Variations

  • Inclusive time: time from start to end including callees; just store each start on the stack and charge end - start + 1 on pop.
  • Half-open timestamps: if an end at t means the call stops at the start of unit t, drop the + 1 and set prev = t.
  • Profiler output: return the longest single call or the deepest stack seen, tracked in the same pass.
  • Rate limits over the same log: a time-window problem like Design Hit Counter instead of a stack.

How to explain it out loud

Fictional example

Pinning down the off-by-one before coding
Candidate
Only one function runs at a time, and it is always the most recent call that has not ended, so a stack of ids tells me who is running.
Candidate
Between two events, the top of the stack owns all the time. I keep prev, the first unit nobody has been charged for.
Interviewer
Why plus one on end events?
Candidate
Because an end at five means the function used unit five too. A start at five means it begins at unit five, so the caller only gets up to four. After an end, the next free unit is six.

In this batch, Validate Stack Sequences also replays pushes and pops, and Simplify Path parses text into stack operations. Online Stock Span is another problem where each new event settles accounts with the top of a stack.

Practicing it with Natively

The off-by-one here is where most spoken explanations wobble. Natively, running on Mac or Windows, can read the log format from a screenshot during practice, suggest the stack-and-marker replay, and transcribe how you explained the end-time rule, so you can hear whether it was clear before an interviewer does. See how it fits into interview practice.

Questions people ask

How do you solve Exclusive Time of Functions?

Replay the log with a stack of function ids and a marker for the first uncharged time unit. On a start, charge the running function t - prev and push. On an end, charge the top t - prev + 1, pop, and set prev to t + 1.

Why add one on end events?

An end timestamp includes its own time unit, while a start timestamp marks the beginning of its unit. So a function ending at t has also used unit t.

How does recursion affect Exclusive Time of Functions?

It needs no special case. The same id can sit on the stack more than once, and its charges are added to the same total.

What is the time complexity of Exclusive Time of Functions?

O(m) for m log lines, since each line is parsed once and causes one push or pop. The stack needs O(m) space in the worst case.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP