Aggregate Transactions by Country for Most Recent Active Period
SQL & DataAuto-graded · 22 test casesLast updated
Tests date handling, filtering, and grouped aggregation to find the latest month with successful records and summarize by region.
Problem Statement
You are building a financial reporting tool that processes transaction records across multiple organizations. Your task is to generate a summary showing how transactions are distributed across different regions for the most recent period that had activity.
Write a function that identifies the latest calendar month (determined by transaction date) containing at least one successful transaction (status 'completed'), then returns aggregated metrics for each organization's headquarters country during that specific month.
Input Format
The function receives two lists:
companies
Each element is a list: [company_id, company_name, hq_country]
company_id(int): Unique identifier for the organizationcompany_name(str): Organization namehq_country(str): Headquarters country code or name
bookings
Each element is a list: [booking_id, company_id, booking_date, booking_amount, status]
booking_id(int): Unique identifier for the transactioncompany_id(int): Reference to the organizationbooking_date(str): Transaction date in ISO format (YYYY-MM-DD)booking_amount(float): Transaction amountstatus(str): One of'completed','failed', or'pending'
Output Format
Return a list of lists, where each inner list contains:
hq_country(str): The headquarters countrytotal_amount(float): Sum of all completed transaction amounts for that country in the target month, rounded to 2 decimal placesbooking_count(int): Count of completed transactions for that country in the target month
Sort results by total_amount descending, then by hq_country ascending (alphabetically).
Rules and Constraints
- Only transactions with status
'completed'count toward determining the active month - A month is "active" only if it contains at least one completed transaction
- Only include transactions that belong to organizations present in the
companieslist - If no completed transactions exist, return an empty list
- Transactions in months containing only failed or pending transactions should be ignored
- Round the total amount to exactly 2 decimal places
- If multiple countries have the same total amount, order them alphabetically by country code
Constraints
- 0 ≤ len(companies) ≤ 10,000
- 0 ≤ len(bookings) ≤ 100,000
- All dates are valid ISO format strings
- Amounts are non-negative
- Status values are always one of:
'completed','failed','pending'
Examples
Example 1
Input: aggregate_latest_month_by_region([[1, 'Acme Corp', 'US'], [2, 'Beta Ltd', 'UK'], [3, 'Gamma GmbH', 'DE']], [[101, 1, '2024-02-15', 10000, 'completed'], [102, 2, '2024-02-28', 15000.5, 'completed'], [103, 1, '2024-03-05', 12000, 'completed'], [104, 2, '2024-03-12', 8000, 'failed'], [105, 3, '2024-03-20', 5000.25, 'completed'], [106, 1, '2024-04-02', 4000, 'failed']])
Output: [['US', 12000, 1], ['DE', 5000.25, 1]]
Hints
Hint 1
First identify which calendar month is the latest one containing any completed transaction, then filter all data to only that month
Hint 2
Build a lookup dictionary mapping company IDs to their countries before processing transactions
Hint 3
Track both the sum and count for each country separately, then combine them at the end
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution requires two distinct phases that must remain separate:
Phase 1: Identify the target month Extract the latest calendar month that contains at least one completed transaction. This determination depends solely on completed transactions—months with only failed or pending transactions don't qualify as "active."
Phase 2: Aggregate within that month Once the target month is identified, sum transaction amounts and count records for each headquarters country, considering only completed transactions in that specific month that belong to known organizations.
A critical mistake to avoid: do not simply take the maximum transaction date across all records. That approach would incorrectly select months containing only failed transactions.
Solution Strategy
-
Build a company lookup: Create a dictionary mapping company IDs to their headquarters countries for fast access during aggregation.
-
Collect completed transactions: Iterate through all bookings and extract only those with status
'completed'. Parse each transaction date and store a tuple of(year, month, company_id, amount). Using year-month tuples enables correct chronological comparison. -
Find the latest active month: Compute the maximum year-month pair across all completed transactions. If no completed transactions exist, return immediately with an empty result.
-
Aggregate by country: Iterate through completed transactions again. For each transaction matching the target month whose company exists in our lookup, accumulate the amount and increment the count for that country.
-
Format and sort: Round each country's total to 2 decimal places, then sort by total descending with country name as a tiebreaker.
The order of operations matters: the month is chosen before checking company existence. This means orphaned transactions (those referencing non-existent companies) still influence which month is selected, but they don't appear in the final output.
Why It Works
Every output row represents a country with at least one completed transaction in the single most recent active month, where the transaction belongs to a known company. Countries without qualifying transactions in the target month naturally disappear during aggregation.
The year-month tuple comparison correctly handles transactions spanning multiple years (e.g., March 2023 vs. March 2024) without collapsing them together.
Complexity
Time: O(C + B + K log K)
- C: number of companies (building the lookup)
- B: number of bookings (two passes through transactions)
- K: number of distinct countries in the output (sorting)
Space: O(C + B)
- Company lookup dictionary
- List of completed transactions
In practice, K is typically small (number of countries), making the sort negligible.
Implementation
from datetime import date
from typing import List
def aggregate_latest_month_by_region(companies: List[List], bookings: List[List]) -> List[List]:
company_country = {row[0]: row[2] for row in companies}
completed = []
for booking in bookings:
booking_id, company_id, booking_date, amount, status = booking
if status == "completed":
d = date.fromisoformat(booking_date)
completed.append((d.year, d.month, company_id, amount))
if not completed:
return []
latest_month = max((year, month) for year, month, _, _ in completed)
totals = {}
for year, month, company_id, amount in completed:
if (year, month) != latest_month or company_id not in company_country:
continue
country = company_country[company_id]
if country not in totals:
totals[country] = [0, 0]
totals[country][0] += amount
totals[country][1] += 1
rows = [[country, round(float(total), 2), count]
for country, (total, count) in totals.items()]
rows.sort(key=lambda row: (-row[1], row[0]))
return rows