Tally Faulty and Clean Submissions per Company
SQL & DataAuto-graded · 17 test casesLast updated
Aggregate two conditional counts per group from two related row lists, keeping groups with no matching rows and handling both boolean and string status values.
Tally Faulty and Clean Submissions per Company
You are given two tables as lists of rows. Write a function that reports, for every company, how many of its submissions were faulty and how many were clean. This is the Python version of a LEFT JOIN + GROUP BY + conditional aggregation query.
Input
companies: a list of rows[company_id, name].entries: a list of rows[entry_id, company_id, created_at, status].
The status field (the fourth element of an entry row) comes in one of two forms:
- A boolean:
Truemeans faulty,Falsemeans clean. - A string:
"buggy"means faulty,"non_buggy"means clean.
Output
Return a list of dictionaries, one per distinct company_id in companies, each with exactly these keys:
"employer_id": the company id"buggy_count": the number of faulty entries for that company"non_buggy_count": the number of clean entries for that company
The list must be sorted by employer_id in ascending order.
Rules
- Every company in
companiesmust appear in the output, even if it has no entries (both counts are then0). - If the same
company_idappears in more than one row ofcompanies, it produces only one output row. - An entry whose
company_iddoes not appear incompaniesis ignored. - A string status other than
"buggy"or"non_buggy"(for example"pending"or"BUGGY"; matching is case-sensitive and exact) is counted in neither column. - A status that is neither a boolean nor a string (for example
None) is counted in neither column. - The
created_atandnamevalues play no role in the result.
Constraints
0 <= len(companies), len(entries) <= 10^5- Company ids and entry ids are integers.
- Each company row has at least 2 elements; each entry row has 4 elements.
- Your solution should run in roughly
O((E + S) + E log E)time, whereEis the number of companies andSthe number of entries.
Examples
Example 1
Input: tally_faulty_clean([[1, 'Acme'], [2, 'Globex'], [3, 'Initech']], [[10, 1, '2025-08-20', True], [11, 1, '2025-08-21', False], [12, 1, '2025-08-22', True], [13, 2, '2025-08-23', False], [14, 2, '2025-08-24', False]])
Output: [{'employer_id': 1, 'buggy_count': 2, 'non_buggy_count': 1}, {'employer_id': 2, 'buggy_count': 0, 'non_buggy_count': 2}, {'employer_id': 3, 'buggy_count': 0, 'non_buggy_count': 0}]
Example 2
Input: tally_faulty_clean([[1, 'Acme'], [2, 'Globex'], [3, 'Initech']], [[10, 1, '2025-08-20', 'buggy'], [11, 1, '2025-08-21', 'non_buggy'], [12, 1, '2025-08-22', 'buggy'], [13, 2, '2025-08-23', 'non_buggy'], [14, 2, '2025-08-24', 'non_buggy']])
Output: [{'employer_id': 1, 'buggy_count': 2, 'non_buggy_count': 1}, {'employer_id': 2, 'buggy_count': 0, 'non_buggy_count': 2}, {'employer_id': 3, 'buggy_count': 0, 'non_buggy_count': 0}]
Hints
Hint 1
Think of the output as one bucket per company. Create every bucket up front with zero counts, so companies without entries are still reported.
Hint 2
Walk through the entries once. Skip any whose company is not a known bucket, and otherwise decide faulty versus clean from the status value.
Hint 3
In Python, `bool` is checked separately from `str`; handle each type explicitly, and let unrecognized strings or other types fall through without incrementing anything. Sort the company ids at the end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem mirrors a SQL query that does a LEFT JOIN from companies to entries, groups by company, and sums two CASE expressions. In Python the same idea takes three steps:
- Seed the buckets (the LEFT JOIN side). Collect the distinct company ids into a set and create a counter pair
{buggy: 0, non_buggy: 0}for each. Because every company gets a bucket before any entry is read, companies with no entries naturally end up with0, 0. Using a set also collapses duplicate company rows, asGROUP BYwould. - Count entries (the conditional aggregation). Scan the entries once. If the entry's company id has no bucket, skip it, since a left join from companies never picks up such rows. Otherwise inspect the status:
- a
boolincrements the faulty counter ifTrue, the clean counter ifFalse; - a
strincrements faulty only for exactly"buggy"and clean only for exactly"non_buggy"; - anything else changes nothing.
- a
- Emit the result (the ORDER BY). Sort the company ids and build one dictionary per id.
Why it is correct
Each entry is examined exactly once and adds at most one to exactly one counter of exactly one known company. Unknown companies, unrecognized strings and non-bool/non-string values are explicitly excluded, matching the stated rules. Every distinct company has a bucket from the start, so none is lost, and sorting the ids gives the required order.
Complexity
With E companies and S entries: building buckets is O(E), the scan is O(S) with constant-time dictionary lookups, and sorting is O(E log E). Total time is O(S + E log E); space is O(E).
Reference solution
from typing import List, Dict
def tally_faulty_clean(companies: List[List], entries: List[List]) -> List[Dict]:
company_ids = {row[0] for row in companies}
counts = {cid: {'buggy': 0, 'non_buggy': 0} for cid in company_ids}
for entry in entries:
cid = entry[1]
status = entry[3]
if cid not in counts:
continue
if isinstance(status, bool):
if status:
counts[cid]['buggy'] += 1
else:
counts[cid]['non_buggy'] += 1
elif isinstance(status, str):
if status == 'buggy':
counts[cid]['buggy'] += 1
elif status == 'non_buggy':
counts[cid]['non_buggy'] += 1
return [
{
'employer_id': cid,
'buggy_count': counts[cid]['buggy'],
'non_buggy_count': counts[cid]['non_buggy'],
}
for cid in sorted(company_ids)
]