Summarise Monthly Revenue by Region from Transaction Records
SQL & DataAuto-graded · 15 test casesLast updated
Tests group-by aggregation over a list-of-dict dataset, requiring candidates to compute per-region monthly totals, fill gaps, and apply a tie-break for ranking.
Monthly Revenue Summary by Region
You are given a list of transaction records. Each record is a dictionary with the following fields:
| Field | Type | Description |
|---|---|---|
"transaction_id" | str | Unique identifier for the transaction |
"region" | str | Region name (non-empty string) |
"month" | str | Month in "YYYY-MM" format |
"amount" | float | Revenue amount (may be negative for refunds) |
Write a function that, given this list of transaction records and a list of query (region, month) pairs, returns for each query the total revenue for that (region, month) combination, rounded to 2 decimal places.
Additionally, the function must return the top-k regions by total revenue across all records (summed over all months), as a list of region names sorted in descending order of total revenue. If two regions have the same total revenue, break the tie alphabetically (ascending) by region name.
Return value
Return a single dict with exactly two keys:
"query_results": a list offloatvalues, one per query in the same order as the inputquerieslist. If a(region, month)pair has no matching records, return0.0for that query."top_k_regions": a list of exactlykregion names (strings). If fewer thankdistinct regions exist in the data, return all distinct regions sorted by the same rule.
Constraints
0 ≤ len(transactions) ≤ 2000- Each
transaction["amount"]is a finite float in the range[-1,000,000, 1,000,000]. 1 ≤ len(queries) ≤ 500- Each query is a two-element list
[region, month]wheremonthmatches the format"YYYY-MM". 1 ≤ k ≤ 50- Region names and month strings may contain uppercase and lowercase letters, digits, hyphens, and spaces.
- Multiple transactions may share the same
(region, month)pair. - Amounts should be summed with standard floating-point arithmetic before rounding.
Examples
Example 1
Input: monthly_revenue_summary([{'transaction_id': 't1', 'region': 'North', 'month': '2024-01', 'amount': 100}, {'transaction_id': 't2', 'region': 'North', 'month': '2024-01', 'amount': 50}, {'transaction_id': 't3', 'region': 'South', 'month': '2024-01', 'amount': 200}, {'transaction_id': 't4', 'region': 'North', 'month': '2024-02', 'amount': 75}], [['North', '2024-01'], ['South', '2024-01'], ['East', '2024-01']], 2)
Output: {'query_results': [150, 200, 0], 'top_k_regions': ['North', 'South']}
Example 2
Input: monthly_revenue_summary([{'transaction_id': 'r1', 'region': 'Alpha', 'month': '2023-06', 'amount': 500}, {'transaction_id': 'r2', 'region': 'Beta', 'month': '2023-06', 'amount': 500}, {'transaction_id': 'r3', 'region': 'Alpha', 'month': '2023-07', 'amount': -100}], [['Alpha', '2023-06'], ['Beta', '2023-06'], ['Alpha', '2023-07'], ['Gamma', '2023-06']], 2)
Output: {'query_results': [500, 500, -100, 0], 'top_k_regions': ['Beta', 'Alpha']}
Example 3
Input: monthly_revenue_summary([], [['North', '2024-01']], 3)
Output: {'query_results': [0], 'top_k_regions': []}
Hints
Hint 1
Use a nested dict (or collections.defaultdict) keyed by (region, month) to accumulate totals, then look up each query in O(1).
Hint 2
For the top-k ranking, separately accumulate each region's grand total across all months, then sort with a key that captures (negative total, region name) so ties resolve alphabetically.
Hint 3
Remember to round each query result to 2 decimal places using Python's built-in round(), and guard against missing keys by defaulting to 0.0.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a straightforward group-by aggregation task, similar to a SQL GROUP BY with SUM, plus a ranked ORDER BY with a tie-break.
Steps
-
Build two aggregation tables in a single pass over the transactions:
region_month[(region, month)]accumulates the totalamountfor each unique(region, month)pair.region_total[region]accumulates the grand total for each region across all months.
Using
collections.defaultdict(float)makes this clean and avoids key-existence checks. -
Answer queries by looking up each
(region, month)pair inregion_month. If the key is absent, the answer is0.0. Round every result to 2 decimal places. -
Rank regions by sorting
region_total.keys()with the sort key(-total, region):- Negating the total gives descending order by revenue.
- The secondary key
region(ascending string) resolves ties alphabetically.
Slice the first
kelements; if fewer thankregions exist, return all of them. -
Return a dict with
"query_results"and"top_k_regions".
Correctness
- The single-pass accumulation correctly handles duplicates (multiple records for the same pair are summed) and negative amounts (refunds reduce the total).
- The
round(..., 2)call matches the problem's precision requirement. - The sort key
(-total, region)guarantees a unique, deterministic ordering. - Returning
region_total.keys()[:k]after sorting handles the case where fewer thankregions exist.
Complexity
- Time: O(T + Q + R log R), where T = number of transactions, Q = number of queries, R = number of distinct regions. The dominant term is usually O(T).
- Space: O(R × M) for the
region_monthtable, where M = distinct months.
from typing import List, Dict, Any
from collections import defaultdict
def monthly_revenue_summary(transactions: list, queries: list, k: int) -> dict:
region_month: Dict[tuple, float] = defaultdict(float)
region_total: Dict[str, float] = defaultdict(float)
for tx in transactions:
region = tx["region"]
month = tx["month"]
amount = tx["amount"]
region_month[(region, month)] += amount
region_total[region] += amount
query_results = []
for q in queries:
region, month = q[0], q[1]
total = region_month.get((region, month), 0.0)
query_results.append(round(total, 2))
sorted_regions = sorted(
region_total.keys(),
key=lambda r: (-region_total[r], r)
)
top_k = sorted_regions[:k]
return {
"query_results": query_results,
"top_k_regions": top_k,
}