Summarize Monthly Sales by Region
SQL & DataAuto-graded · 15 test casesLast updated
Tests ability to perform group-by aggregation over a list of transaction records, computing per-region monthly totals and counts.
Monthly Sales Summary by Region
You are given a list of sales transaction records. Each record is a dictionary with the following fields:
"region"— a non-empty string identifying the sales region (e.g."North","South")"month"— an integer from1to12representing the calendar month"amount"— a positive float representing the sale amount
Write a function that aggregates these records and returns a summary list. Each entry in the summary corresponds to one unique (region, month) pair that appears in the input, and contains:
"region"— the region string"month"— the month integer"total_amount"— the sum of allamountvalues for that group, rounded to 2 decimal places"num_transactions"— the count of records in that group
The returned list must be sorted ascending first by region (lexicographic), then by month (numeric) as a tie-breaker.
If the input list is empty, return an empty list.
Constraints
0 ≤ len(transactions) ≤ 2000- Each
"region"is a non-empty string containing only printable ASCII characters. - Each
"month"is an integer with1 ≤ month ≤ 12. - Each
"amount"is a float with0.0 < amount ≤ 1_000_000.0. - Multiple records may share the same
(region, month)pair. - Region comparison is case-sensitive (
"north"and"North"are different regions).
Examples
Example 1
Input: summarize_monthly_sales([{'region': 'North', 'month': 3, 'amount': 120.5}, {'region': 'South', 'month': 3, 'amount': 200}, {'region': 'North', 'month': 3, 'amount': 80.75}, {'region': 'North', 'month': 1, 'amount': 500}])
Output: [{'region': 'North', 'month': 1, 'total_amount': 500, 'num_transactions': 1}, {'region': 'North', 'month': 3, 'total_amount': 201.25, 'num_transactions': 2}, {'region': 'South', 'month': 3, 'total_amount': 200, 'num_transactions': 1}]
Example 2
Input: summarize_monthly_sales([{'region': 'East', 'month': 6, 'amount': 999.99}, {'region': 'East', 'month': 6, 'amount': 0.01}])
Output: [{'region': 'East', 'month': 6, 'total_amount': 1000, 'num_transactions': 2}]
Example 3
Input: summarize_monthly_sales([])
Output: []
Hints
Hint 1
Use a dictionary keyed by (region, month) tuples to accumulate running totals and counts in a single pass.
Hint 2
After building the aggregation dictionary, convert it to a list of result dicts and sort by (region, month).
Hint 3
Remember to round the final total_amount to 2 decimal places — do this after summing all amounts for a group, not during accumulation.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a classic group-by aggregation: accumulate a running sum and count for each unique (region, month) key, then format and sort the results.
Steps:
- Iterate once over all transaction records. Use two dictionaries (or one dict of tuples) keyed by
(region, month)— one for the running total, one for the count. - Build the result list by converting each key-value pair into the required output dictionary. Round
total_amountto 2 decimal places at this stage (after all additions are complete) to minimize floating-point accumulation issues. - Sort the result list by
(region, month)— Python's tuple comparison handles lexicographic string order followed by numeric month order automatically.
Why it is correct:
- A single linear pass guarantees all records are processed.
- Rounding only at the end (not on each addition) reduces intermediate floating-point error.
- Sorting by
(region, month)with Python's stable sort produces the unique required ordering.
Complexity:
- Time: O(n log n) — the single pass is O(n); sorting the at-most min(n, 12·R) unique groups (where R is number of distinct regions) is O(n log n) in the worst case.
- Space: O(n) for the aggregation dictionaries and result list.
def summarize_monthly_sales(transactions: list) -> list:
from collections import defaultdict
totals = defaultdict(float)
counts = defaultdict(int)
for record in transactions:
key = (record["region"], record["month"])
totals[key] += record["amount"]
counts[key] += 1
result = []
for (region, month), total in totals.items():
result.append({
"region": region,
"month": month,
"total_amount": round(total, 2),
"num_transactions": counts[(region, month)],
})
result.sort(key=lambda x: (x["region"], x["month"]))
return result