#1661
Average Time of Process per Machine
EasyDatabaseHash MapArray
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)
This approach leverages a single pass through the activity log to efficiently calculate the total time and count of processes for each machine. By using a dictionary to track start times, we can directly compute the duration when we encounter an 'end' activity.
⚙️
Algorithm
6 steps- 1Step 1: Initialize two dictionaries to store total time and count of processes for each machine.
- 2Step 2: Iterate through each activity in the log.
- 3Step 3: For 'start' activities, store the timestamp in a dictionary with a key of (machine_id, process_id).
- 4Step 4: For 'end' activities, calculate the duration using the stored 'start' timestamp, update the total time and count for the machine.
- 5Step 5: After processing all activities, compute the average time for each machine.
- 6Step 6: Return the results as a table.
solution.py18 lines
1def average_time_per_machine(activities):
2 from collections import defaultdict
3 total_time = defaultdict(float)
4 count = defaultdict(int)
5 start_time = {}
6
7 for activity in activities:
8 machine_id, process_id, activity_type, timestamp = activity
9 if activity_type == 'start':
10 start_time[(machine_id, process_id)] = timestamp
11 elif activity_type == 'end':
12 total_time[machine_id] += timestamp - start_time[(machine_id, process_id)]
13 count[machine_id] += 1
14
15 result = []
16 for machine_id in total_time:
17 result.append((machine_id, total_time[machine_id] / count[machine_id]))
18 return resultℹ
Complexity note: The complexity is O(n) because we make a single pass through the activities, storing and calculating values in constant time for each entry.
- 1Understanding the relationship between 'start' and 'end' activities is crucial for calculating the total time accurately.
- 2Using dictionaries (or hash maps) allows for efficient lookups and updates, significantly improving performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.