Compute Spending Totals by Worker, Journey, and Type
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests efficient multi-key aggregation using hash maps to group and sum records in a single pass over large datasets.
You receive a collection of spending records. Each record is a dictionary containing:
employee_id(string): identifier for the worker who incurred the expensetrip_id(string): identifier for the journey during which the expense occurredcategory(string): type of expense (examples:"MEAL","HOTEL","TRANSPORT")amount(integer): cost in cents or smallest currency unit
Write a function that computes three separate aggregations and returns them in a single dictionary:
- Global worker totals: sum of all expenses for every worker in the dataset
- Journey breakdown: sum of expenses per journey, limited to one specified worker
- Category breakdown: sum of expenses per category, limited to the same specified worker
The function accepts a list of records and one employee_id string. It must return a dictionary with exactly three keys:
"employee_totals": maps everyemployee_idin the input to their total spending (integer)"trip_totals": maps eachtrip_idbelonging to the specified employee to the total spent on that journey"category_totals": maps eachcategoryused by the specified employee to the total spent in that category
If the specified employee_id does not appear in the records, "trip_totals" and "category_totals" must be empty dictionaries (not None).
Constraints
- 0 ≤ number of records ≤ 1,000,000
- All string fields are non-empty
- Amounts may be zero or negative (refunds)
- Keys are case-sensitive:
"MEAL"and"meal"are distinct categories - Your solution should process the records efficiently; avoid repeated full scans
Examples
Example 1
Input: compute_spending_totals([{'employee_id': 'e1', 'trip_id': 't1', 'category': 'MEAL', 'amount': 25}, {'employee_id': 'e1', 'trip_id': 't1', 'category': 'HOTEL', 'amount': 120}, {'employee_id': 'e2', 'trip_id': 't2', 'category': 'TRANSPORT', 'amount': 40}, {'employee_id': 'e1', 'trip_id': 't2', 'category': 'MEAL', 'amount': 15}], 'e1')
Output: {'employee_totals': {'e1': 160, 'e2': 40}, 'trip_totals': {'t1': 145, 't2': 15}, 'category_totals': {'MEAL': 40, 'HOTEL': 120}}
Example 2
Input: compute_spending_totals([{'employee_id': 'alice', 'trip_id': 'trip-1', 'category': 'MEAL', 'amount': 10}, {'employee_id': 'alice', 'trip_id': 'trip-1', 'category': 'MEAL', 'amount': 20}, {'employee_id': 'bob', 'trip_id': 'trip-1', 'category': 'MEAL', 'amount': 99}], 'alice')
Output: {'employee_totals': {'alice': 30, 'bob': 99}, 'trip_totals': {'trip-1': 30}, 'category_totals': {'MEAL': 30}}
Example 3
Input: compute_spending_totals([], 'missing')
Output: {'employee_totals': {}, 'trip_totals': {}, 'category_totals': {}}
Hints
Hint 1
All three aggregations are sum-by-key operations over the same input; consider computing them together in a single traversal.
Hint 2
Use hash maps with .get(key, 0) to accumulate totals without checking existence first.
Hint 3
Only two of the three outputs are filtered by employee; the global employee totals include everyone.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each of the three outputs is a sum grouped by a key. Rather than scanning the input three times, recognize that you can build all three hash maps in parallel during a single pass.
Algorithm:
- Initialize three empty dictionaries:
employee_totals,trip_totals, andcategory_totals. - Iterate through each record once.
- For every record, add its amount to
employee_totals[employee_id]. - If the record's employee matches the target
employee_id, also accumulate the amount into:trip_totals[trip_id]category_totals[category]
- Return the three dictionaries bundled in the required structure.
Use dict.get(key, 0) to handle the first occurrence of each key cleanly without an explicit existence check.
Why It Works
Each record contributes to exactly one employee total bucket. When that employee is the one we are filtering for, the record also contributes to exactly one trip bucket and one category bucket. Because addition is associative and commutative, the order of records does not matter. No record is counted twice or skipped, so the final sums are exact.
As a sanity check: the sum of all values in trip_totals equals the sum of all values in category_totals, and both equal employee_totals[employee_id] when that employee appears in the data.
Complexity
- Time: O(n), where n is the number of records. Each record is visited once, and hash map operations (insert and update) are O(1) on average.
- Space: O(E + T + C), where E is the number of distinct employees, T is the number of distinct trips for the target employee, and C is the number of distinct categories for that employee. In the worst case this is O(n), but typically much smaller.
Edge Cases
- Empty input: all three dictionaries are empty.
- Target employee not in the data:
employee_totalsis still populated for all employees present;trip_totalsandcategory_totalsare empty. - Negative or zero amounts: summed as-is; a key can have a total of zero.
- Duplicate keys within the same employee: amounts accumulate, which is correct.
from typing import List, Dict
def compute_spending_totals(records: List[Dict[str, object]], employee_id: str) -> Dict[str, Dict[str, int]]:
employee_totals = {}
trip_totals = {}
category_totals = {}
for record in records:
emp = record["employee_id"]
trip = record["trip_id"]
cat = record["category"]
amt = record["amount"]
employee_totals[emp] = employee_totals.get(emp, 0) + amt
if emp == employee_id:
trip_totals[trip] = trip_totals.get(trip, 0) + amt
category_totals[cat] = category_totals.get(cat, 0) + amt
return {
"employee_totals": employee_totals,
"trip_totals": trip_totals,
"category_totals": category_totals,
}