Average Time of Process per Machine solution and explanation
9 more videos on this problem
Average Time of Process per Machine | Leetcode 1661 | Crack SQL Interviews in 50 Qs #mysqlLearn With Chirag · 9:02 · 35K views
10. Average Time of Process per Machine | SQL Interview Questions and AnswersStart Practicing · 12:08 · 26K views
LeetCode 1661: Average Time of Process per Machine [SQL]Frederik Müller · 8:16 · 16K views
Leetcode | Easy | 1661. Average Time of Process per Machine | SQL | JOINSoftware Interviews Prep · 8:30 · 756 views
SQL Interview Questions and Answers Series | LeetCode | 10. Average Time of Process Per MachineNishtha Nagar · 7:40 · 715 views
1661. "Average Time of Process per Machine" | SQL 50 | Leetcode | SQL Interview | Self join | CTEManvi Jha · 9:53 · 584 views
FAANG TASK#10 - Average Time of Process per Machine | Tuitions Tonight | LEETCODETuitions Tonight · 7:47 · 401 views
Master SQL with VanAmsen: Solve 'Average Time of Process per Machine' from LeetCode | 1661vanAmsen · 6:51 · 391 views
1661. Average Time of Process per Machine | SQL | LEETCODE | Easy Explaination | College PlacementsSheCodes · 17:02 · 347 views
LeetCode 1661: Average Time of Process per Machine (SQL) | Amazon Interview QuestionsData Science Pathshala · 5:42 · 284 views
The problem
Table: Activity
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| machine_id | int |
| process_id | int |
| activity_type | enum |
| timestamp | float |
+----------------+---------+
The table shows the user activities for a factory website.
(machine_id, process_id, activity_type) is the primary key (combination of columns with unique values) of this table.
machine_id is the ID of a machine.
process_id is the ID of a process running on the machine with ID machine_id.
activity_type is an ENUM (category) of type ('start', 'end').
timestamp is a float representing the current time in seconds.
'start' means the machine starts the process at the given timestamp and 'end' means the machine ends the process at the given timestamp.
The 'start' timestamp will always be before the 'end' timestamp for every (machine_id, process_id) pair.
It is guaranteed that each (machine_id, process_id) pair has a 'start' and 'end' timestamp.
There is a factory website that has several machines each running the same number of processes. Write a solution to find the average time each machine takes to complete a process.
The time to complete a process is the 'end' timestamp minus the 'start' timestamp. The average time is calculated by the total time to complete every process on the machine divided by the number of processes that were run.
The resulting table should have the machine_id along with the average time as processing_time, which should be rounded to 3 decimal places.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input: Activity table: +------------+------------+---------------+-----------+ | machine_id | process_id | activity_type | timestamp | +------------+------------+---------------+-----------+ | 0 | 0 | start | 0.712 | | 0 | 0 | end | 1.520 | | 0 | 1 | start | 3.140 | | 0 | 1 | end | 4.120 | | 1 | 0 | start | 0.550 | | 1 | 0 | end | 1.550 | | 1 | 1 | start | 0.430 | | 1 | 1 | end | 1.420 | | 2 | 0 | start | 4.100 | | 2 | 0 | end | 4.512 | | 2 | 1 | start | 2.500 | | 2 | 1 | end | 5.000 | +------------+------------+---------------+-----------+ Output: +------------+-----------------+ | machine_id | processing_time | +------------+-----------------+ | 0 | 0.894 | | 1 | 0.995 | | 2 | 1.456 | +------------+-----------------+ Explanation: There are 3 machines running 2 processes each. Machine 0's average time is ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894 Machine 1's average time is ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995 Machine 2's average time is ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456
Approach overview
Problem Overview: Each process on a machine has two records: a start event and an end event with timestamps. The goal is to compute the average processing time for every machine_id. For each process, subtract the start time from the end time, then average those durations per machine.
Approach 1: Using HashMap for Storing Start and End Times (O(n) time, O(n) space)
Iterate through all activity records and store the start timestamp of each process in a hash map keyed by (machine_id, process_id). When the corresponding end record appears, compute the duration by subtracting the stored start time from the end time. Maintain another map that tracks total processing time and process count per machine. At the end, divide total time by count to produce the average for each machine. Hash lookups make each pairing operation constant time, giving O(n) total time complexity with O(n) auxiliary space. This approach is straightforward and mirrors how you'd process event logs in production systems. It relies on efficient key lookup using a HashMap.
Approach 2: Sorting and Linear Scan Method (O(n log n) time, O(1) extra space)
Sort the activity records by machine_id, process_id, and timestamp. After sorting, each process’s start and end events appear next to each other. Perform a single linear scan: when a start record is encountered, the following record will be the matching end. Compute the duration immediately and accumulate totals per machine. Because sorting dominates the runtime, the complexity becomes O(n log n) with constant extra space if the sort is done in-place. This approach works well when input ordering is unpredictable and you want deterministic pairing through ordering, using concepts from sorting and sequential scans.
Both solutions compute identical results: total duration per machine divided by the number of completed processes. The logic is similar to aggregations commonly used in database problems where events must be paired and summarized.
Recommended for interviews: The HashMap approach is typically expected. It runs in linear time, directly models the pairing of start and end events, and demonstrates strong understanding of event processing with constant-time lookups. The sorting method still shows solid reasoning but is less optimal due to the O(n log n) sorting cost.
Approach 1: Using HashMap for Storing Start and End Times
This approach involves using a data structure like a HashMap to store the start and end timestamps for each process on each machine. For each machine and process, compute the time taken using these timestamps. Then, calculate the average processing time for all machines.
# Python solution using a dictionary to track start and end times
from collections import defaultdict
activity_data = [
(0, 0, 'start', 0.712),
(0, 0, 'end', 1.520),
(0, 1, 'start', 3.140),
(0, 1, 'end', 4.120),
(1, 0, 'start', 0.550),
(1, 0, 'end', 1.550),
(1, 1, 'start', 0.430),
(1, 1, 'end', 1.420),
(2, 0, 'start', 4.100),
(2, 0, 'end', 4.512),
(2, 1, 'start', 2.500),
(2, 1, 'end', 5.000)
]
machine_times = defaultdict(list)
for machine_id, process_id, activity_type, timestamp in activity_data:
machine_times[(machine_id, process_id)].append(timestamp)
avg_times = defaultdict(float)
process_count = defaultdict(int)
for (machine_id, process_id), times in machine_times.items():
if times[0] < times[1]:
process_time = times[1] - times[0]
else:
process_time = times[0] - times[1]
avg_times[machine_id] += process_time
process_count[machine_id] += 1
result = []
for machine_id in avg_times:
average_time = round(avg_times[machine_id] / process_count[machine_id], 3)
result.append((machine_id, average_time))
# Output the result
def print_result(result):
print("+------------+-----------------+")
print("| machine_id | processing_time |")
print("+------------+-----------------+")
for machine_id, avg_time in result:
print(f"| {machine_id} | {avg_time:.3f} |")
print("+------------+-----------------+")
print_result(result)// JavaScript solution using a map to track start and end times
const activityData = [
{machine_id: 0, process_id: 0, activity_type: 'start', timestamp: 0.712},
{machine_id: 0, process_id: 0, activity_type: 'end', timestamp: 1.520},
{machine_id: 0, process_id: 1, activity_type: 'start', timestamp: 3.140},
{machine_id: 0, process_id: 1, activity_type: 'end', timestamp: 4.120},
{machine_id: 1, process_id: 0, activity_type: 'start', timestamp: 0.550},
{machine_id: 1, process_id: 0, activity_type: 'end', timestamp: 1.550},
{machine_id: 1, process_id: 1, activity_type: 'start', timestamp: 0.430},
{machine_id: 1, process_id: 1, activity_type: 'end', timestamp: 1.420},
{machine_id: 2, process_id: 0, activity_type: 'start', timestamp: 4.100},
{machine_id: 2, process_id: 0, activity_type: 'end', timestamp: 4.512},
{machine_id: 2, process_id: 1, activity_type: 'start', timestamp: 2.500},
{machine_id: 2, process_id: 1, activity_type: 'end', timestamp: 5.000}
];
const machineTimes = new Map();
for (const {machine_id, process_id, activity_type, timestamp} of activityData) {
const key = `${machine_id},${process_id}`;
if (!machineTimes.has(key)) machineTimes.set(key, []);
machineTimes.get(key).push(timestamp);
}
const avgTimes = new Map();
const processCount = new Map();
for (const [key, times] of machineTimes.entries()) {
const [machine_id] = key.split(',').map(Number);
const processTime = Math.abs(times[1] - times[0]);
if (!avgTimes.has(machine_id)) avgTimes.set(machine_id, 0);
if (!processCount.has(machine_id)) processCount.set(machine_id, 0);
avgTimes.set(machine_id, avgTimes.get(machine_id) + processTime);
processCount.set(machine_id, processCount.get(machine_id) + 1);
}
const result = [];
for (const [machine_id, totalTime] of avgTimes) {
const averageTime = parseFloat((totalTime / processCount.get(machine_id)).toFixed(3));
result.push({ machine_id, processing_time: averageTime });
}
console.table(result);This Python solution uses a dictionary to collect timestamps by process and machine. It then calculates process times and averages them by machine.
Time Complexity: O(n), where n is the number of rows in the input. We iterate once through the list to collect timestamps.
Space Complexity: O(m), where m is the number of unique machine and process combinations.
Approach 2: Sorting and Linear Scan Method
In this approach, we first sort the data by machine_id and process_id, ensuring that each start and end appears consecutively. We then do a single linear scan to compute the time taken for each process and maintain a cumulative sum for each machine, eventually computing the average processing time.
// Java solution with sorting and linear scan
import java.util.*;
class Activity {
int machine_id;
int process_id;
String activity_type;
double timestamp;
public Activity(int m_id, int p_id, String a_type, double time) {
this.machine_id = m_id;
this.process_id = p_id;
this.activity_type = a_type;
this.timestamp = time;
}
}
public class AverageProcessingTime {
public static void main(String[] args) {
List<Activity> activities = new ArrayList<>();
activities.add(new Activity(0, 0, "start", 0.712));
activities.add(new Activity(0, 0, "end", 1.520));
activities.add(new Activity(0, 1, "start", 3.140));
activities.add(new Activity(0, 1, "end", 4.120));
activities.add(new Activity(1, 0, "start", 0.550));
activities.add(new Activity(1, 0, "end", 1.550));
activities.add(new Activity(1, 1, "start", 0.430));
activities.add(new Activity(1, 1, "end", 1.420));
activities.add(new Activity(2, 0, "start", 4.100));
activities.add(new Activity(2, 0, "end", 4.512));
activities.add(new Activity(2, 1, "start", 2.500));
activities.add(new Activity(2, 1, "end", 5.000));
Map<Integer, Double> totalTimes = new HashMap<>();
Map<Integer, Integer> processCounts = new HashMap<>();
// Sort the data by machine_id and process_id
activities.sort((a, b) -> {
if (a.machine_id != b.machine_id) return a.machine_id - b.machine_id;
return a.process_id - b.process_id;
});
for (int i = 0; i < activities.size(); i += 2) {
Activity start = activities.get(i);
Activity end = activities.get(i + 1);
double processTime = end.timestamp - start.timestamp;
totalTimes.put(start.machine_id, totalTimes.getOrDefault(start.machine_id, 0.0) + processTime);
processCounts.put(start.machine_id, processCounts.getOrDefault(start.machine_id, 0) + 1);
}
// Calculate average process times
List<String> results = new ArrayList<>();
for (Map.Entry<Integer, Double> entry : totalTimes.entrySet()) {
int machine_id = entry.getKey();
double averageTime = entry.getValue() / processCounts.get(machine_id);
results.add(String.format("Machine ID: %d, Processing Time: %.3f", machine_id, averageTime));
}
// Output results
results.forEach(System.out::println);
}
}// C++ solution using sorting and linear scan
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iomanip>
struct Activity {
int machine_id;
int process_id;
std::string activity_type;
double timestamp;
};
int main() {
std::vector<Activity> activities = {
{0, 0, "start", 0.712},
{0, 0, "end", 1.520},
{0, 1, "start", 3.140},
{0, 1, "end", 4.120},
{1, 0, "start", 0.550},
{1, 0, "end", 1.550},
{1, 1, "start", 0.430},
{1, 1, "end", 1.420},
{2, 0, "start", 4.100},
{2, 0, "end", 4.512},
{2, 1, "start", 2.500},
{2, 1, "end", 5.000}
};
std::unordered_map<int, double> totalTimes;
std::unordered_map<int, int> processCounts;
// Sort activities based on machine_id and process_id
std::sort(activities.begin(), activities.end(), [](const Activity &a, const Activity &b) {
if (a.machine_id != b.machine_id) return a.machine_id < b.machine_id;
return a.process_id < b.process_id;
});
for (size_t i = 0; i < activities.size(); i += 2) {
const Activity &start = activities[i];
const Activity &end = activities[i + 1];
double processTime = end.timestamp - start.timestamp;
totalTimes[start.machine_id] += processTime;
processCounts[start.machine_id]++;
}
// Output average processing time per machine
std::cout << "+------------+-----------------+" << std::endl;
std::cout << "| machine_id | processing_time |" << std::endl;
std::cout << "+------------+-----------------+" << std::endl;
for (const auto &entry : totalTimes) {
int machine_id = entry.first;
double averageTime = entry.second / processCounts[machine_id];
std::cout << "| " << machine_id << " | " << std::fixed << std::setprecision(3) << averageTime << " |" << std::endl;
}
std::cout << "+------------+-----------------+" << std::endl;
return 0;
}This Java implementation sorts the activity data and employs a dual-index scan to compute and accumulate the process time for each machine. The average times are then calculated and displayed.
Time Complexity: O(n log n) due to sorting the list of activities.
Space Complexity: O(m), for storing accumulated processing times and counts by machine.
Approach 3: Grouping and Aggregation
We can group by machine_id and use the AVG function to calculate the average time consumption of all process tasks on each machine. Since each process task on the machine has a pair of start and end timestamps, the time consumption of each process task can be calculated by subtracting the start timestamp from the end timestamp. Therefore, we can use the CASE WHEN or IF function to calculate the time consumption of each process task, and then use the AVG function to calculate the average time consumption of all process tasks on each machine.
Note that each machine has 2 process tasks, so we need to multiply the calculated average time consumption by 2.
# Write your MySQL query statement below
SELECT
machine_id,
ROUND(
AVG(
CASE
WHEN activity_type = 'start' THEN -timestamp
ELSE timestamp
END
) * 2,
3
) AS processing_time
FROM Activity
GROUP BY 1;Approach 4: Default Approach
# Write your MySQL query statement below
SELECT
machine_id,
ROUND(AVG(IF(activity_type = 'start', -1, 1) * timestamp) * 2, 3) AS processing_time
FROM Activity
GROUP BY 1;Complexity comparison
| Approach | Complexity |
|---|---|
| Using HashMap for Storing Start and End Times | Time Complexity: O(n), where n is the number of rows in the input. We iterate once through the list to collect timestamps. |
| Sorting and Linear Scan Method | Time Complexity: O(n log n) due to sorting the list of activities. |
| Grouping and Aggregation | – |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| HashMap for Start-End Pairing | O(n) | O(n) | Best general solution when events arrive in arbitrary order |
| Sorting and Linear Scan | O(n log n) | O(1) extra | Useful when sorting is acceptable or memory usage must stay minimal |
Frequently asked questions
Is Average Time of Process per Machine easy or hard?
Average Time of Process per Machine is classified as an Easy problem. The core idea is straightforward: pair start and end events, compute the duration, and average the results per machine. The challenge mainly lies in organizing the data efficiently.
Average Time of Process per Machine Python/Java solution
Python and JavaScript implementations typically use dictionaries or objects as hash maps to pair start and end events. Java and C++ solutions often rely on sorting the records and performing a linear scan to compute durations, though hash maps can also be used in those languages.
How to solve Average Time of Process per Machine in O(n)?
Iterate through the activity list and store start timestamps in a hash map keyed by machine_id and process_id. When an end event is encountered, subtract the stored start time to compute the processing duration. Accumulate total duration and process count per machine, then divide total time by count to get the average.
What is the best approach for Average Time of Process per Machine?
The HashMap pairing approach is the most efficient. Store the start timestamp for each (machine_id, process_id) pair, then compute the duration when the end record appears. This processes all records in O(n) time with O(n) space while directly aggregating totals per machine.
Is Average Time of Process per Machine asked at Google/Amazon/Meta?
Problems involving log pairing, event processing, and aggregation appear frequently in interviews at companies like Amazon and Google. This question tests the ability to match related events and compute aggregated metrics efficiently using hash maps or database-style grouping.
What data structure is used in Average Time of Process per Machine?
A HashMap is the primary data structure used in the optimal solution. It stores the start timestamp for each process and allows constant-time lookup when the corresponding end event appears. Additional maps or counters track the accumulated time and process count per machine.
What is the time complexity of Average Time of Process per Machine?
The optimal solution runs in O(n) time using a HashMap to match start and end events. Each record is processed once with constant-time lookups. A sorting-based alternative takes O(n log n) time because the activity records must be ordered before scanning.
