Leetcode 636: Exclusive Time of Functions

grid47
grid47
Exploring patterns and algorithms
Sep 4, 2024 7 min read

A timeline of function executions, where the exclusive time for each function is highlighted and softly glowing.
Solution to LeetCode 636: Exclusive Time of Functions Problem

You are given a list of logs representing the execution of n functions on a single-threaded CPU. Each log contains a function’s ID, whether the function has started or ended, and the timestamp of the event. The goal is to calculate the exclusive time of each function, which is the total time the function spends executing, excluding the time spent on other nested function calls.
Problem
Approach
Steps
Complexity
Input: You are given a list of logs formatted as strings with the structure {function_id}:{start|end}:{timestamp}. The logs indicate when a function starts or ends at a given timestamp.
Example: n = 2, logs = ["0:start:0", "1:start:2", "1:end:5", "0:end:6"]
Constraints:
• 1 <= n <= 100
• 1 <= logs.length <= 500
• 0 <= function_id < n
• 0 <= timestamp <= 10^9
• No two start events will happen at the same timestamp.
• No two end events will happen at the same timestamp.
Output: Return the exclusive time for each function as an array, where the value at the ith index represents the exclusive time for function i.
Example: [3, 4]
Constraints:
• The output will be an array of n integers representing the exclusive times for each function.
Goal: Calculate the exclusive time for each function based on the logs.
Steps:
• Iterate through the logs and simulate the execution of the functions using a stack.
• Track the start and end times for each function call and compute the total time spent executing each function.
Goal: The solution must handle all values of n and logs within the given constraints efficiently.
Steps:
• The function must process logs of length up to 500 efficiently.
• Ensure that the time spent on each function is calculated correctly, considering recursive calls.
Assumptions:
• Each function has a start and end log.
• The logs will be given in chronological order.
Input: n = 2, logs = ["0:start:0", "1:start:2", "1:end:5", "0:end:6"]
Explanation: Function 0 starts at time 0 and runs for 2 units of time, function 1 starts at time 2 and runs for 4 units. Function 0 resumes at time 6 and runs for 1 unit, making the total exclusive time of function 0 equal to 3, and function 1 equal to 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus