#636
Exclusive Time of Functions
MediumArrayStackStackArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution utilizes a stack to keep track of active function calls and calculates the exclusive time efficiently by maintaining a current time variable. This approach allows us to handle nested function calls seamlessly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array to hold the exclusive time for each function and a stack to track active function calls.
- 2Step 2: Iterate through each log entry, updating the current time based on whether the log indicates a 'start' or 'end'.
- 3Step 3: When a function ends, calculate the time spent and update the exclusive time for the function at the top of the stack.
solution.py18 lines
1# Full working Python code
2
3def exclusiveTime(n, logs):
4 exclusive_time = [0] * n
5 stack = []
6 prev_time = 0
7 for log in logs:
8 func_id, status, time = log.split(':')
9 func_id, time = int(func_id), int(time)
10 if status == 'start':
11 if stack:
12 exclusive_time[stack[-1]] += time - prev_time
13 stack.append(func_id)
14 prev_time = time
15 else:
16 exclusive_time[stack.pop()] += time - prev_time + 1
17 prev_time = time + 1
18 return exclusive_timeℹ
Complexity note: This complexity is linear because we process each log entry exactly once. The stack operations (push and pop) are also efficient, keeping the overall time complexity to O(n).
- 1Understanding the stack structure is crucial for managing nested function calls.
- 2Accurate time tracking is essential to calculate exclusive time correctly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.