Exclusive Time of Functions

MediumStackmonotonic stack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A single-threaded CPU runs a program with n functions labeled 0 to n - 1. Calls may nest (including recursive calls). You are given the execution logs in chronological order; each entry is a string "{id}:start:{t}" or "{id}:end:{t}". Timestamps are integer time units. "id:start:t" means the function begins running at the **beginning** of unit t; "id:end:t" means it stops at the **end** of unit t. So a call logged as start 2 and end 5 covers units 2, 3, 4, and 5. The *exclusive time* of a function is the total number of units it spent running itself, excluding time spent in calls it made. Return an array where index i holds the exclusive time of function i (summed over all of its calls; 0 if it was never called).

Examples

Input: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]
Output: [3,4]
Function 0 runs units 0-1 and 6 (3 units); function 1 runs units 2-5 (4 units).
Input: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"]
Output: [8]
All 8 units from 0 to 7 belong to function 0 across its recursive calls.
Input: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"]
Output: [7,1]
Function 1 runs only during unit 6; every other unit from 0 to 7 is function 0.

Constraints

  • 1 <= n <= 100
  • 2 <= logs.length <= 500
  • 0 <= id < n
  • 0 <= t <= 10^9, and logs are sorted by timestamp
  • Every start has a matching end, and no two start events share a timestamp

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More monotonic stack problems