Per-Row Offset From Group Average in a Record List
Arrays & HashingAuto-graded · 14 test casesLast updated
Tests group-then-broadcast logic: compute each group's mean over a list of dict records, then attach each row's difference from its group mean while preserving order.
You are given a list of activity records. Each record is a dictionary describing one user's messaging activity for a day. Every record contains at least these keys:
user_id: an integer identifying the userteam_id: an integer identifying the team the user belongs tomessages_sent: a non-negative integer, the number of messages sentdate: a string such as"2024-05-01"
Records may also contain other keys.
For each record, determine how far its messages_sent is from the average messages_sent of all records that share the same team_id. Return a new list of records in which every record is a copy of the original with one extra key, "delta_from_team_mean", whose value is:
messages_sent - (mean of messages_sent over all records with the same team_id)
Rules
- The returned list has the same length and the same order as the input.
- Every original key and value is kept unchanged in the output record. Only
"delta_from_team_mean"is added. - Do not modify the input list or the dictionaries inside it.
- The team mean is taken over records, not over distinct users. If a user appears in several records, each record counts separately.
- A
messages_sentof0is a real value and counts toward the mean. - Use true (floating point) division for the mean, so that means such as
5.5are not truncated. A team with a single record has a delta of0. - If the input list is empty, return an empty list.
Constraints
0 <= len(rows) <= 10^5messages_sentis an integer with0 <= messages_sent <= 10^6- Every record has the keys
team_idandmessages_sent team_idvalues are hashable (integers in the tests)
Examples
Example 1
Input: compute_team_offsets([{'user_id': 1, 'team_id': 10, 'messages_sent': 8, 'date': '2024-05-01'}, {'user_id': 2, 'team_id': 10, 'messages_sent': 3, 'date': '2024-05-01'}, {'user_id': 3, 'team_id': 20, 'messages_sent': 15, 'date': '2024-05-02'}, {'user_id': 4, 'team_id': 20, 'messages_sent': 9, 'date': '2024-05-02'}, {'user_id': 5, 'team_id': 30, 'messages_sent': 0, 'date': '2024-05-03'}])
Output: [{'user_id': 1, 'team_id': 10, 'messages_sent': 8, 'date': '2024-05-01', 'delta_from_team_mean': 2.5}, {'user_id': 2, 'team_id': 10, 'messages_sent': 3, 'date': '2024-05-01', 'delta_from_team_mean': -2.5}, {'user_id': 3, 'team_id': 20, 'messages_sent': 15, 'date': '2024-05-02', 'delta_from_team_mean': 3}, {'user_id': 4, 'team_id': 20, 'messages_sent': 9, 'date': '2024-05-02', 'delta_from_team_mean': -3}, {'user_id': 5, 'team_id': 30, 'messages_sent': 0, 'date': '2024-05-03', 'delta_from_team_mean': 0}]
Hints
Hint 1
This is a two-step idea: first summarize each team, then use that summary on every individual row.
Hint 2
Make one pass over the records to accumulate, per team, the sum of messages_sent and the number of records. Use dictionaries keyed by team_id.
Hint 3
Make a second pass in the original order: copy each record with dict(row), then add messages_sent minus total/count for its team. Use / rather than // so means like 5.5 stay exact.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each output row depends on a statistic of its group (the team mean), yet the output must keep one row per input row. That is an "aggregate, then broadcast back" pattern, the same thing pandas does with groupby(...).transform("mean") or SQL does with AVG(...) OVER (PARTITION BY team_id).
We do it in two linear passes:
- Aggregate pass. Walk through the records and, for each
team_id, accumulate the total ofmessages_sentand the number of records. - Broadcast pass. Walk through the records again in their original order. For each one, copy the dictionary and add
delta_from_team_mean = messages_sent - total[team] / count[team].
Why it is correct
- After the first pass,
total[t] / count[t]is exactly the arithmetic mean ofmessages_sentover all records withteam_id == t. - The second pass visits every record once, in order, so the output is a one-to-one, order-preserving mapping of the input.
- Copying with
dict(row)keeps all original keys and leaves the caller's data untouched. - Any team seen in the second pass was counted in the first, so
count[t] >= 1and division by zero cannot happen. - True division yields floats, so means like
5.5are not truncated. A single-record team gets a delta of0. An empty input yields an empty list.
Complexity
- Time: O(n), two passes with O(1) dictionary operations each.
- Space: O(n) for the output plus O(k) for the per-team totals and counts, where k is the number of distinct teams.
Reference solution
from collections import defaultdict
from typing import Dict, List
def compute_team_offsets(rows: List[Dict]) -> List[Dict]:
totals = defaultdict(int)
counts = defaultdict(int)
for row in rows:
team = row["team_id"]
totals[team] += row["messages_sent"]
counts[team] += 1
result = []
for row in rows:
copied = dict(row)
team = row["team_id"]
copied["delta_from_team_mean"] = row["messages_sent"] - totals[team] / counts[team]
result.append(copied)
return result