Per-Account Usage Means Above a Threshold
SQL & DataAuto-graded · 15 test casesLast updated
Group readings by account id, keep accounts whose unrounded mean CPU, memory, or disk usage tops 50, then emit half-up rounded, email-sorted records.
Two lists of plain dictionaries describe a hosting database.
customers holds account records, each with:
"id": an integer account identifier, unique across accounts."email": a string address. Distinct accounts may carry an identical email string.
readings holds metric records, each with:
"customer_id": the account the reading belongs to."cpu_usage","memory_usage","disk_usage": numeric percentages.
For each account that has at least one reading in readings, take the arithmetic mean of its cpu_usage values, the mean of its memory_usage values, and the mean of its disk_usage values. An account qualifies when at least one of these three means is strictly greater than 50. Judge this on the raw means, before any rounding — a mean of exactly 50 does not qualify.
Produce a list of dictionaries, one per qualifying account, each holding exactly these keys:
"email""average_cpu_usage""average_memory_usage""average_disk_usage"
The three averages must each be the mean rounded to two decimal places with half-up rounding (a tie at the third decimal moves away from zero). Whether an account qualifies is still decided on the unrounded means, so a mean such as 50.004 is included even though it displays as 50.0.
Ordering rules:
- Sort the result ascending by
email. Accounts that share an email may appear in any relative order among themselves.
Further rules:
- Accounts with no readings at all are left out.
- Readings whose
"customer_id"matches no account are ignored. - Never discard individual readings based on how high or low a value is before averaging.
- Every qualifying account gets its own output record, even when two accounts share the same email.
Return the result as a plain Python list of dictionaries.
Constraints
0 <= len(customers) <= 10^50 <= len(readings) <= 10^5- Account
"id"values are unique;"customer_id"values inreadingsare integers. - Usage values are non-negative numbers (not
None). - Each qualifying account contributes exactly one record; the total never exceeds
len(customers).
Examples
Example 1
Input: accounts_over_usage_threshold([{'id': 1, 'email': '[email protected]'}, {'id': 2, 'email': '[email protected]'}, {'id': 3, 'email': '[email protected]'}], [{'customer_id': 1, 'cpu_usage': 60, 'memory_usage': 40, 'disk_usage': 45}, {'customer_id': 1, 'cpu_usage': 40, 'memory_usage': 60, 'disk_usage': 45}, {'customer_id': 2, 'cpu_usage': 50, 'memory_usage': 50, 'disk_usage': 50}, {'customer_id': 3, 'cpu_usage': 20, 'memory_usage': 30, 'disk_usage': 70}])
Output: [{'email': '[email protected]', 'average_cpu_usage': 20, 'average_memory_usage': 30, 'average_disk_usage': 70}]
Example 2
Input: accounts_over_usage_threshold([{'id': 1, 'email': '[email protected]'}, {'id': 2, 'email': '[email protected]'}, {'id': 3, 'email': '[email protected]'}], [{'customer_id': 1, 'cpu_usage': 50, 'memory_usage': 50, 'disk_usage': 50}, {'customer_id': 2, 'cpu_usage': 51, 'memory_usage': 49, 'disk_usage': 10}])
Output: [{'email': '[email protected]', 'average_cpu_usage': 51, 'average_memory_usage': 49, 'average_disk_usage': 10}]
Hints
Hint 1
Key the running totals on the account id, not the email, so two accounts that share an address keep their averages apart.
Hint 2
Decide who qualifies using the raw means; round only the three numbers you place in the output.
Hint 3
Add a tiny epsilon before calling round so binary float noise and banker's rounding don't pull x.xx5 values down.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat it as a grouped aggregation with the filter applied afterwards.
- Aggregate. Make a single pass over
readings, keeping a running CPU sum, memory sum, disk sum, and a count for everycustomer_id. This is the grouping step. Keying on the account id rather than the email is what keeps two accounts with the same address separate. - Join and test. Walk
customers. If an account has no tally, skip it — no readings means no averages, so it can never qualify. Otherwise divide each of the three sums by the count, and keep the account when at least one mean is> 50. This comparison uses the raw, unrounded means. - Round for display. Only the values written to the output are rounded. Because Python floats are binary, a value like
50.125is often stored as50.12499…, androundalso uses banker's rounding on exact halves; adding1e-10beforehand pushes such values to the expected half-up result for non-negative percentages. - Sort. Order the records ascending by
email. Python's sort is stable, so accounts with identical emails stay in input order, which the task permits.
Why it is correct
- Each reading is added to exactly one account's tally, so the sums cover precisely that account's readings and the count is exactly how many there are — the three means are correct.
- No reading is filtered at the row level. Dropping a low reading before averaging would inflate the mean, which the task forbids, and this approach never does it.
- Qualification is decided on unrounded means, matching the rule that a mean like 50.004 counts while an exact 50 does not.
- Only one mean above 50 is needed, so the check is an OR across the three values, not an AND.
- Accounts with no readings never get a tally and are excluded; readings whose
customer_idmatches no account sit in tallies no account ever looks up, so they are ignored. - Rounding happens after the decision, so displayed values never influence who qualifies.
Complexity
Let M be the number of readings and C the number of accounts.
- Time: O(M + C log C) — one pass over the readings, one pass over the accounts, and a sort of at most C output records.
- Space: O(K + C), where K is the number of distinct account ids that appear in
readings, for the tally map and the output list.
Edge cases covered
- Account with zero readings: excluded.
- Two accounts sharing an email: two separate records (or one, if only one qualifies).
- Mean exactly 50: excluded, because the comparison is strict.
- Mean a hair above 50, e.g. 50.004: included, and displayed rounded.
- Only one of the three means above 50: included.
- An account with a single reading: its means equal that reading's values.
- Readings pointing at no account: ignored.
- Half-cent means such as x.xx5: rounded half-up.
from collections import defaultdict
from typing import Dict, List
def accounts_over_usage_threshold(customers: List[Dict[str, int | str]], readings: List[Dict[str, int | float]]) -> List[Dict[str, int | float | str]]:
# account id -> [cpu sum, memory sum, disk sum, reading count]
tallies = defaultdict(lambda: [0.0, 0.0, 0.0, 0])
for reading in readings:
slot = tallies[reading["customer_id"]]
slot[0] += reading["cpu_usage"]
slot[1] += reading["memory_usage"]
slot[2] += reading["disk_usage"]
slot[3] += 1
output = []
for account in customers:
slot = tallies.get(account["id"])
if slot is None: # no readings: nothing to average, account drops out
continue
n = slot[3]
means = [slot[0] / n, slot[1] / n, slot[2] / n]
if means[0] > 50 or means[1] > 50 or means[2] > 50:
output.append({
"email": account["email"],
"average_cpu_usage": round(means[0] + 1e-10, 2),
"average_memory_usage": round(means[1] + 1e-10, 2),
"average_disk_usage": round(means[2] + 1e-10, 2),
})
output.sort(key=lambda record: record["email"])
return output