MySQL 1661.sql
SELECT machine_id, ROUND((finish - init) / processes, 3) AS processing_time
FROM (SELECT machine_id,
COUNT(*) / 2 AS processes,
SUM(IF(activity_type = 'start', timestamp, 0)) AS init,
SUM(IF(activity_type = 'end', timestamp, 0)) AS finish
FROM Activity
GROUP BY machine_id) s
Difficulty
and has an acceptance rate of about 67% (1+ million submissions).
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The statement calculates an average processing time per machine by first summarizing activity records and then deriving a per-process duration. It works in two logical phases: an inner aggregation that collapses raw activity rows into per-machine totals, and an outer projection that turns those totals into a rounded average time.
Key Steps
Phase 1 - Conditional aggregation
The inner query groups rows by machine_id. For each group it computes three values: the number of processes, the summed start timestamps, and the summed end timestamps.
SELECT
machine_id,
COUNT(*) / 2 AS processes,
SUM(IF(activity_type = 'start', timestamp, 0)) AS init,
SUM(IF(activity_type = 'end', timestamp, 0)) AS finish
FROM Activity
GROUP BY machine_id
COUNT(*) / 2assumes that each process generates exactly two rows (a start and an end). Dividing the row count by two yields the process count.- The
SUM(IF(...))constructs act as conditional aggregates: rows whoseactivity_typematches the predicate contribute theirtimestamp; all other rows add zero. This eliminates the need for separate joins or sub-queries for start and end events.
Phase 2 - Deriving the average processing time
The outer query receives the aggregated columns as a derived table (s). It computes the average duration by subtracting the total start time from the total end time, dividing by the number of processes, and rounding the result to three decimal places.
SELECT
machine_id,
ROUND((finish - init) / processes, 3) AS processing_time
FROM ( ... ) s
The expression (finish - init) / processes yields the mean elapsed time per process for each machine, and ROUND(..., 3) formats the output to three fractional digits.
Edge Cases Handled
When a machine’s activity log is incomplete-e.g., a missing start or end row-the conditional sums still produce a numeric result because non-matching rows contribute zero. Consequently, the finish - init difference reflects only the timestamps that actually exist, avoiding null propagation.
If a machine has an odd number of activity rows, the division COUNT(*) / 2 yields a non-integer process count. The subsequent arithmetic still works because MySQL treats the divisor as a floating-point value, so the average duration is computed on a fractional process count rather than causing a runtime error.
Machines without any activity rows are naturally excluded from the result set because the GROUP BY clause only produces groups that contain at least one row.
Performance Optimizations
The query leverages conditional aggregation (SUM(IF(...))) to compute start and end totals in a single scan of the Activity table. This approach avoids the overhead of self-joins or multiple sub-queries that would otherwise require additional passes over the data.
By performing the division and rounding in the outer layer, the engine can materialize the intermediate aggregates once and reuse them for the final calculation, reducing redundant computation.
Grouping by the indexed column machine_id (assuming an index exists) enables the database to quickly locate and aggregate rows per machine, minimizing I/O and CPU work during the aggregation phase.
Overall, the design keeps the data flow linear: a single aggregation pass followed by a lightweight projection, which is efficient for large activity logs.
ELI5 - Simplified Explanation
Imagine a big factory workshop filled with toy robots. Each robot has a special ID number to identify it. This code acts like a very organized scorekeeper watching these robots finish their jobs.
First, the computer looks at all the robots and groups them together by their ID numbers so it can keep track of each robot separately. For every robot, the computer looks at all the times the robot said it was starting a task and all the times it said it was done. It adds up all the start times and keeps them in a box, and it adds up all the end times and keeps those in another box. It also counts how many times each robot worked.
Once the computer has those numbers ready in its boxes, it does a little bit of math. It takes the total finish time and subtracts the total start time to figure out how long the work took overall. Then it divides that by the number of jobs the robot did to see how fast each task happened. Finally, it makes sure the answer is not too long by rounding it to three decimal places. The end result is a simple list showing just the robot ID and the speed of their work.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||
|---|---|---|---|---|---|---|
| author | solutions | |||||
| www | AlgoMonster | C++ | Java | Python | TS | |
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| Progiez | C++ | Java | Python | |||
| github | everthis | SQL | ||||
| suxrobGM | SQL | |||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| Progiez | C++, Java, Python | |||||
| everthis | SQL | |||||
| suxrobGM | SQL |
Videos
Solved On The Same Day
- problem 415: Add Strings
- problem 463: Island Perimeter
- problem 541: Reverse String II
- problem 1211: Queries Quality and Percentage
- problem 1251: Average Selling Price
- problem 1280: Students and Examinations
- problem 1327: List the Products Ordered in a Period
- problem 1378: Replace Employee ID With The Unique Identifier
- problem 1407: Top Travellers
- problem 1484: Group Sold Products By The Date
- problem 1517: Find Users With Valid E-Mails
- problem 1527: Patients With a Condition
- problem 1581: Customer Who Visited but Did Not Make Any Transactions
- problem 1587: Bank Account Summary II
- problem 1633: Percentage of Users Attended a Contest
- problem 1667: Fix Names in a Table
- problem 1683: Invalid Tweets
- problem 1693: Daily Leads and Partners
- problem 1729: Find Followers Count
- problem 1731: The Number of Employees Which Report to Each Employee
- problem 1741: Find Total Time Spent by Each Employee
- problem 1757: Recyclable and Low Fat Products
- problem 1789: Primary Department for Each Employee
- problem 1795: Rearrange Products Table
- problem 1873: Calculate Special Bonus
- problem 1890: The Latest Login in 2020
- problem 1965: Employees With Missing Information
- problem 1978: Employees Whose Manager Left the Company
- problem 2356: Number of Unique Subjects Taught by Each Teacher
- problem 166: Fraction to Recurring Decimal
- problem 223: Rectangle Area
- problem 240: Search a 2D Matrix II
- problem 318: Maximum Product of Word Lengths
- problem 357: Count Numbers with Unique Digits
- problem 394: Decode String
- problem 1158: Market Analysis I
- problem 1341: Movie Rating
- problem 1492: The kth Factor of n
- problem 1498: Number of Subsequences That Satisfy the Given Sum Condition
- problem 1907: Count Salary Categories
- problem 1934: Confirmation Rate
- problem 2405: Optimal Partition of String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality