Problem 1661

Abstract / Summary

Calculate the average processing time per machine using given start and end times for each job.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
7 lines | 351 bytes | submitted September 7, 2023 | GitHub  

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 67% (1+ million submissions).
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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(*) / 2 assumes 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 whose activity_type matches the predicate contribute their timestamp; 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.52 | σ = 1.50

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
11 links | 6 authors | 5 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

29 easy 13 medium
43 solutions   September 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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