Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: A single-threaded CPU log has entries 'id:start:t' and 'id:end:t' (an end at t covers time unit t). Functions can call each other. Compute each function's exclusive time.

Problem: A single-threaded CPU log has entries 'id:start:t' and 'id:end:t' (an end at t covers time unit t). Functions can call each other. Compute each function's exclusive time.
def excl(n, logs):
    res, st, prev = [0] * n, [], 0
    for log in logs:
        fid, typ, t = log.split(':'); fid, t = int(fid), int(t)
        if typ == 'start':
            if st: res[st[-1]] += t - prev
            st.append(fid); prev = t
        else:
            res[st.pop()] += t - prev + 1; prev = t + 1
    return res
print(excl(3, ["0:start:0", "1:start:2", "2:start:3", "2:end:4", "1:end:6", "0:end:9"]))
What is printed?
  1. A. [5, 3, 2]
  2. B. [4, 3, 3]
  3. C. [3, 4, 2]
  4. D. [5, 2, 2]

Correct answer: A. [5, 3, 2]

Function 0 runs units 0–1 and 7–9 (5 units); function 1 runs 2 and 5–6 (3 units); function 2 runs 3–4 (2 units). The '+1' on end entries and prev = t + 1 handle the inclusive end timestamps; total 10 = 0..9.

More Coding Interview Problems questions

Exams that ask this topic