Taro Logo

Exclusive Time of Functions

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+7
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.5K views
Topics:
ArraysStacks

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 <= 100
  • 2 <= logs.length <= 500
  • 0 <= function_id < n
  • 0 <= timestamp <= 109
  • No two start events will happen at the same timestamp.
  • No two end events will happen at the same timestamp.
  • Each function has an "end" log for each "start" log.

Solution


Clarifying Questions

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:

  1. Are the logs guaranteed to be strictly well-formed, meaning every start log has a corresponding end log in correct LIFO order?
  2. What is the format of the log strings (e.g., "function_id:start:timestamp"), and are the IDs and timestamps always valid non-negative integers?
  3. Are the logs guaranteed to be sorted chronologically by their timestamps?
  4. Can multiple functions have start or end events at the exact same timestamp, and how should overlapping or zero-duration function executions be handled?
  5. What should be returned if the logs list is empty or `n` is 0?

Brute Force Solution

Approach

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:

  1. Create a detailed calendar that covers every single tick of time from when the first function starts to when the last function ends.
  2. Look at the first tick of time on your calendar and check which function was actually running during that specific moment according to the execution logs.
  3. Add one point of time to that specific function's total score.
  4. Move to the very next tick of time on the calendar and figure out which function was active during that moment.
  5. Add one point to that function's score as well.
  6. Repeat this checking process for every single tick of time from start to finish.
  7. At the end, tally up all the points each function accumulated across the entire calendar to get their total exclusive times.

Code Implementation

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_times

Big(O) Analysis

Time Complexity
O(T + N) – The cost is driven by the total duration of time ticks from the very beginning to the very end of the execution logs, let us call this T, alongside the number of log entries N. For every single tick of time across the massive calendar, the algorithm must step through and check which function is active to add points to its score. Additionally, we must process all N log entries to understand when functions start and stop to build this timeline. This leads to approximately T plus N operations, which simplifies to O(T + N).
Space Complexity
O(n) – The space complexity is driven by the calendar data structure that must cover every single tick of time from when the first function starts to when the last function ends. As the total execution duration grows, the size of this auxiliary calendar expands linearly with the total number of time units. Additionally, the solution requires a score-tracking array whose size corresponds to the number of unique functions, which remains bound by the input constraints. Therefore, the extra memory required grows in direct proportion to the timeline and function count, culminating in a linear space complexity relative to the size of the execution timeframe.

Optimal Solution

Approach

To 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:

  1. Read through the history of function events one by one in the exact order they happened.
  2. Whenever a function starts, remember that it is now the active worker and pause whatever was working before it.
  3. Whenever a function stops, look at how much time passed since the last event and credit that time to the function that was just working.
  4. Account for any pauses or interruptions by subtracting the time spent on nested tasks from the parent task that temporarily stepped aside.
  5. Continue this process until every single start and stop event has been completely processed.
  6. Combine all the collected time blocks for each individual function to get their final total durations.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – The cost is driven by iterating through the list of logs exactly once, where n represents the total number of log entries. During this single pass, pushing to and popping from the stack takes constant time for each log entry. Summing the constant-time stack operations across all n logs results in n operations. Therefore, the time complexity simplifies to O(n).
Space Complexity
O(n) – The auxiliary space is primarily driven by the stack used to track currently active function IDs and the resulting array that stores the exclusive time for each of the N functions. As the number of log events and nested functions increases, the stack can grow up to a maximum depth of N elements in the worst-case scenario. Additionally, the output results array requires space proportional to the number of unique functions. Combining the stack and the results vector, the extra memory scales linearly with the input size N.

Edge Cases

Minimum input where n equals 1 and logs contain a single function starting and ending at timestamp 0 and 1
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The algorithm correctly attributes the exclusive time by tracking the previous timestamp and updating the duration upon function termination.