On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1.
Function calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.
You are given a list logs, where logs[i] represents the ith log message formatted as a string "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively.
A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3.
Return the exclusive time of each function in an array, where the value at the ith index represents the exclusive time for the function with ID i.
Example 1:
Input: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"] Output: [3,4] Explanation: Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.
Example 2:
Input: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"] Output: [8] Explanation: Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.
Example 3:
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] Explanation: Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.
Constraints:
1 <= n <= 1002 <= logs.length <= 5000 <= function_id < n0 <= timestamp <= 109"end" log for each "start" log.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine tracking the exact amount of time every single function spends running on a single processor by looking at a giant timeline of every function starting and stopping. The brute force approach involves creating a massive calendar or timeline where every single unit of time from the very beginning to the very end is examined one by one.
Here's how the algorithm would work step-by-step:
def exclusive_time(function_count, logs):
parsed_logs = []
for entry in logs:
function_id, action, timestamp = entry.split(":")
parsed_logs.append((int(function_id), action, int(timestamp)))
total_duration = parsed_logs[-1][2] + 1
timeline_slots = [0] * total_duration
active_function_stack = []
for function_id, action, timestamp in parsed_logs:
if action == "start":
active_function_stack.append((function_id, timestamp))
else:
current_function, start_time = active_function_stack.pop()
for time_tick in range(start_time, timestamp + 1):
timeline_slots[time_tick] = current_function
if len(active_function_stack) > 0:
resumed_function, resumed_start = active_function_stack[-1]
for time_tick in range(start_time, timestamp + 1):
timeline_slots[time_tick] = resumed_function
active_function_stack[-1] = (resumed_function, timestamp + 1)
# We map every single time tick on the calendar to the active function running at that exact moment
function_exclusive_times = [0] * function_count
for executed_function_id in timeline_slots:
function_exclusive_times[executed_function_id] += 1
# Tallying all accumulated points gives the total exclusive execution time for each function
return function_exclusive_timesTo track how long each function runs, we can use a mental stack to keep track of which task is currently active. As time moves forward and we process logs of functions starting and stopping, we can attribute every unit of time to the function that was actually working at that exact moment.
Here's how the algorithm would work step-by-step:
class Solution:
def exclusiveTime(self, total_functions: int, execution_logs: list[str]) -> list[str]:
exclusive_times = [0] * total_functions
function_stack = []
previous_timestamp = 0
for log_entry in execution_logs:
parts = log_entry.split(':')
function_id = int(parts[0])
event_type = parts[1]
timestamp = int(parts[2])
# A new function starts, so we attribute elapsed time to the currently active function.
if event_type == 'start':
if function_stack:
exclusive_times[function_stack[-1]] += timestamp - previous_timestamp
function_stack.append(function_id)
previous_timestamp = timestamp
# A function ends, so we include its final execution tick and resume the parent task.
else:
exclusive_times[function_stack.pop()] += timestamp - previous_timestamp + 1
previous_timestamp = timestamp + 1
# All events have been fully processed, returning the total durations for each function.
return exclusive_times| Case | How to Handle |
|---|---|
| Minimum input where n equals 1 and logs contain a single function starting and ending at timestamp 0 and 1 | A single push and pop operation on the stack correctly calculates the exclusive time as 2 units. |
| Deeply nested recursive functions where multiple functions start consecutively without any ending | The stack data structure naturally tracks the active context, allowing the current function to be interrupted and correctly resumed later. |
| Functions that execute for zero time units, such as starting and ending at the exact same timestamp | The duration formula accounts for zero-length execution by adding 1 to the difference between end and start timestamps. |
| Large scale inputs with millions of log entries and maximum allowed timestamp values | Using an iterative stack approach with linear time complexity O(N) ensures the algorithm scales efficiently without stack overflow. |
| Extremely high timestamp values causing potential integer overflow in languages with strict numeric bounds | Using standard 64-bit integers for timestamp calculations prevents arithmetic overflow during large time duration computations. |
| Sequential non-nested functions where one function ends immediately before another starts | The algorithm correctly attributes the exclusive time by tracking the previous timestamp and updating the duration upon function termination. |