Monthly Line Output Report with Running Totals and Defect Percent
SQL & DataAuto-graded · 15 test casesLast updated
Group daily production records by line and month, add a per-line running total, and compute each month's defect percentage from summed counts.
Monthly Line Output Report
A factory records one entry per assembly line per production day. Each entry is a list with five values, in this order:
log_id: unique id of the entry (int)line_id: id of the assembly line (int)production_date: date string inYYYY-MM-DDformatunits_produced: units made that day (int)units_defective: units from that day flagged as defective (int)
Write a function that turns these daily entries into a monthly report, with one output row for every (line_id, month) pair that appears in the input.
Each output row is a list of five values:
line_idmonth: the stringYYYY-MM, taken from the date. Different years are different months, so2023-01and2024-01are separate groups.total_produced: the sum ofunits_producedfor that line in that monthcumulative_production: the running total oftotal_producedfor that line, adding up its months in chronological order up to and including the current one. The running total restarts for each line.defect_rate:100 * (sum of units_defective in the month) / (sum of units_produced in the month), returned as a float and not rounded. It must be computed from the monthly sums, not by averaging daily rates.
Output order
Sort the rows by line_id ascending, then by month ascending. Months with no entries for a line produce no row, and the running total carries over to that line's next month that has data.
Constraints
- Dates span multiple years.
units_producedis greater than 0 in every entry, so the rate never divides by zero.units_defectiveis a non-negative integer and never exceedsunits_produced.- Entries may arrive in any order.
- If the input is empty, return an empty list.
Examples
Example 1
Input: monthly_line_report([[1, 101, '2023-01-05', 100, 5], [2, 101, '2023-01-20', 200, 10], [3, 101, '2023-02-10', 150, 0]])
Output: [[101, '2023-01', 300, 300, 5], [101, '2023-02', 150, 450, 0]]
Hints
Hint 1
Reduce each entry to a key made of the line id and the first 7 characters of the date, and keep two running sums per key: produced and defective.
Hint 2
Sort the keys so each line's months are contiguous and in chronological order. A YYYY-MM string sorts correctly as plain text.
Hint 3
Walk through the sorted keys while keeping a separate cumulative counter per line. Compute the rate from the month's summed counts as defective * 100.0 / produced.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has two stages, and they must run in this order.
- Aggregate by (line, month). Take the month as the first 7 characters of the date string (
YYYY-MM). Because the year is part of the key, the same calendar month in different years stays separate. Use a dictionary keyed by(line_id, month)that stores the summed units produced and the summed units defective. - Walk the groups in sorted order. Sorting the keys orders them by line and then by month. A
YYYY-MMstring compares chronologically as plain text. For each group:- Add its
total_producedto that line's running counter. This gives the cumulative value. - Compute
defective * 100.0 / producedfrom the monthly sums. - Append the row.
- Add its
Why it is correct
- Grouping on the full
YYYY-MMprefix means every entry lands in exactly one bucket, and no two years are merged. - Sorting by
(line_id, month)guarantees that each line's months are visited in chronological order. The per-line counter therefore holds the sum of all earlier and current months for that line, and it restarts for every new line. - The rate uses the summed monthly counts, so busy days weigh more than quiet ones, as required. Production is always positive, so the division is safe.
- Months with no data never become keys, so they produce no rows. The cumulative counter simply continues from the previous month that does have data.
Complexity
Let N be the number of entries and G the number of distinct (line, month) groups.
- Time: O(N) to aggregate, plus O(G log G) to sort the groups.
- Space: O(G) for the aggregates and the output.
Reference solution
from collections import defaultdict
from typing import List
def monthly_line_report(rows: List[List]) -> List[List]:
monthly = defaultdict(lambda: [0, 0])
for log_id, line_id, production_date, units_produced, units_defective in rows:
month = production_date[:7]
monthly[(line_id, month)][0] += units_produced
monthly[(line_id, month)][1] += units_defective
result = []
cumulative = defaultdict(int)
for line_id, month in sorted(monthly):
total_produced, total_defective = monthly[(line_id, month)]
cumulative[line_id] += total_produced
defect_rate = total_defective * 100.0 / total_produced
result.append([line_id, month, total_produced, cumulative[line_id], defect_rate])
return result