Katkat

Compute Exclusive Execution Times

MetaSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to manage state in nested processes using a stack data structure to track the exclusive execution time of functions based on a log of start and end events.

Problem Statement

You are given an integer n representing the number of functions running in a single-threaded CPU, and a list of logs where each entry is a string in the format "function_id:event:timestamp".

  • function_id is the ID of the function (0 to n-1).
  • event is either "start" or "end".
  • timestamp is the absolute time when the event occurred.

A function is called when it starts and completes when it ends. A function may be interrupted by another function call. The CPU is single-threaded, meaning only one function runs at any given time. When a function is interrupted, its execution is paused until the interrupting function completes.

Your task is to return a list of integers representing the exclusive execution time of each function, ordered by their function_id. Exclusive time is the total time spent by a function, excluding the time spent by any functions it called.

Function Signature

def exclusive_time(n: int, logs: List[str]) -> List[int]:

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 from 0 to 2 (duration 2) and from 5 to 6 (duration 1). Total: 3. Function 1 runs from 2 to 6 (duration 4). Total: 4.

Constraints

  • 1 <= n <= 100
  • 1 <= logs.length <= 500
  • Timestamps are non-decreasing.
  • The logs are valid: nested functions are always closed before their parents.

Edge Cases

  • A function calling itself recursively.
  • Functions that finish exactly when another starts.

Hints

Hint 1

Use a stack to keep track of the function IDs currently being executed, as the last function started is the first one to end.

Hint 2

Maintain a variable to keep track of the 'previous timestamp' to calculate the duration of the function currently at the top of the stack.

Hint 3

When a "start" occurs, add the interval since the last timestamp to the function currently on the stack, then push the new function; when an "end" occurs, add the interval including the end timestamp and pop the stack.

Follow-up questions

  • How would your approach change if the logs were not sorted by timestamp?
  • What if the functions were executed on a multi-threaded system where functions could run in parallel?
  • How can you optimize the space complexity if the number of nested functions is very large?