Find Top-Funded Municipalities and Their Leading Projects
SQL & DataAuto-graded · 18 test casesLast updated
Aggregate relational records over a specific date window to identify peak entities with tie preservation at multiple hierarchical levels.
You are analyzing development grants allocated across various municipalities. You are given three datasets representing municipalities, local projects, and financial grant records.
Your goal is to identify all municipalities that achieved the highest aggregate funding received throughout the full calendar year of 2024 (specifically covering timestamps from 2024-01-01 00:00:00 up to, but excluding, 2025-01-01 00:00:00).
For each municipality that achieves this maximum total 2024 funding, you must also determine the project or projects within that municipality that received the highest individual 2024 funding total.
Input Formats
villages: A list of dictionaries, where each dictionary contains:"village_id"(int): Unique identifier for the municipality."village_name"(str): Name of the municipality.
projects: A list of dictionaries, where each dictionary contains:"project_id"(int): Unique identifier for the project."village_id"(int): Id of the associated municipality."project_name"(str): Name of the project.
project_fundings: A list of dictionaries, where each dictionary contains:"funding_id"(int): Unique identifier for the grant transaction."project_id"(int): Id of the recipient project."amount"(intorfloat): Disbursed funds."funded_at"(str): Timestamp formatted as"YYYY-MM-DD HH:MM:SS".
Rules & Requirements
- Date Filtering: Only sum disbursements where
2024-01-01 00:00:00 <= funded_at < 2025-01-01 00:00:00. - Aggregation:
- A project's 2024 total funding is the sum of all valid 2024 disbursements it received (0 if none).
- A municipality's 2024 total funding is the sum of the 2024 funding totals of all projects registered under it.
- Preserve Ties at Both Levels:
- If multiple municipalities share the global maximum total 2024 funding, include all of them.
- For any selected municipality, if multiple projects share the maximum 2024 funding within that municipality, include all of them.
- Empty Municipalities/Projects: A municipality with no registered projects does not produce any output rows.
- Output Structure: Return a list of lists, where each inner list contains:
[village_id, village_name, village_total_funding, project_id, project_name, project_total_funding]Convert funding totals to standard floating-point numbers (float). - Ordering: Sort the output rows in ascending order by
village_id, and then byproject_id.
Constraints
0 <= len(villages) <= 10000 <= len(projects) <= 50000 <= len(project_fundings) <= 20000amount >= 0- All IDs are positive integers.
Examples
Example 1
Input: top_funded_village_projects([{'village_id': 1, 'village_name': 'Greenfield'}, {'village_id': 2, 'village_name': 'Riverdale'}, {'village_id': 3, 'village_name': 'Oakridge'}], [{'project_id': 101, 'village_id': 1, 'project_name': 'Solar Well'}, {'project_id': 102, 'village_id': 1, 'project_name': 'Road Repair'}, {'project_id': 103, 'village_id': 2, 'project_name': 'Clinic Expansion'}, {'project_id': 104, 'village_id': 2, 'project_name': 'School Library'}, {'project_id': 105, 'village_id': 3, 'project_name': 'Irrigation Canal'}], [{'funding_id': 1, 'project_id': 101, 'amount': 3000, 'funded_at': '2024-03-15 10:00:00'}, {'funding_id': 2, 'project_id': 101, 'amount': 2000, 'funded_at': '2024-06-01 09:00:00'}, {'funding_id': 3, 'project_id': 102, 'amount': 5000, 'funded_at': '2024-08-10 12:00:00'}, {'funding_id': 4, 'project_id': 103, 'amount': 6000, 'funded_at': '2024-04-20 11:00:00'}, {'funding_id': 5, 'project_id': 104, 'amount': 4000, 'funded_at': '2024-09-05 14:00:00'}, {'funding_id': 6, 'project_id': 105, 'amount': 9000, 'funded_at': '2023-12-31 23:59:59'}])
Output: [[1, 'Greenfield', 10000, 101, 'Solar Well', 5000], [1, 'Greenfield', 10000, 102, 'Road Repair', 5000], [2, 'Riverdale', 10000, 103, 'Clinic Expansion', 6000]]
Hints
Hint 1
Filter and sum funding allocations per project for the year 2024 first before combining with municipality data.
Hint 2
Using `Decimal` for precision during aggregation avoids floating-point inaccuracy when evaluating ties.
Hint 3
Identify the maximum municipality total across all municipalities, filter for tied municipalities, and then find the top project(s) per tied municipality.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To solve this problem cleanly, we can perform a hierarchical aggregation process using hash maps:
-
Date Filtering and Initial Aggregation: Parse each transaction's
funded_attimestamp. Filter out entries that fall outside the range[2024-01-01 00:00:00, 2025-01-01 00:00:00). Sum the funding amounts perproject_id. To avoid potential floating-point representation errors when checking for ties, standardDecimalobjects are used for accumulation. -
Municipality-Level Aggregation: Map each project to its corresponding municipality. Accumulate the project totals to find each municipality's total 2024 funding. Initialize every known municipality with an initial funding sum of
0so that unfunded municipalities are accounted for correctly. -
Peak Determination & Tie Handling:
- Determine the maximum aggregate funding across all municipalities (
max_village_total). - Iterate through municipalities with totals matching
max_village_total. - For each qualifying municipality, find the maximum project total within that specific municipality (
max_project_total). - Retain every project whose individual total equals
max_project_total.
- Determine the maximum aggregate funding across all municipalities (
-
Deterministic Sorting: Iterate through the municipalities sorted by
village_idin ascending order, and within each municipality, iterate through its top projects sorted byproject_idin ascending order.
Complexity
- Time Complexity: $\mathcal{O}(N_F + N_P \log N_P + N_V \log N_V)$, where $N_F$ is the number of funding entries, $N_P$ is the number of projects, and $N_V$ is the number of municipalities. Parsing dates and aggregating funding takes $\mathcal{O}(N_F)$. Mapping and sorting entities by ID takes logarithmic time relative to the number of projects and municipalities.
- Space Complexity: $\mathcal{O}(N_V + N_P)$ to store dictionary mappings for aggregate funding totals and relationships between municipalities and projects.
from collections import defaultdict
from datetime import datetime
from decimal import Decimal
from typing import Dict, List
def top_funded_village_projects(
villages: List[Dict],
projects: List[Dict],
project_fundings: List[Dict]
) -> List[List]:
start_date = datetime.fromisoformat("2024-01-01 00:00:00")
end_date = datetime.fromisoformat("2025-01-01 00:00:00")
# Step 1: Aggregate funding per project for 2024
project_totals = defaultdict(Decimal)
for funding in project_fundings:
funded_at = datetime.fromisoformat(funding["funded_at"])
if start_date <= funded_at < end_date:
project_totals[funding["project_id"]] += Decimal(str(funding["amount"]))
# Step 2: Group projects by municipality and compute municipality totals
projects_by_village = defaultdict(list)
village_totals = {v["village_id"]: Decimal("0") for v in villages}
for proj in projects:
p_id = proj["project_id"]
v_id = proj["village_id"]
p_total = project_totals[p_id]
projects_by_village[v_id].append((proj, p_total))
village_totals[v_id] += p_total
if not village_totals:
return []
# Step 3: Identify the maximum funding total among municipalities
max_village_total = max(village_totals.values())
village_by_id = {v["village_id"]: v for v in villages}
results = []
# Step 4: Extract winning municipalities and their winning projects
for v_id in sorted(village_totals.keys()):
if village_totals[v_id] != max_village_total:
continue
v_projects = projects_by_village[v_id]
if not v_projects:
continue
max_project_total = max(t for _, t in v_projects)
sorted_projects = sorted(v_projects, key=lambda x: x[0]["project_id"])
for proj, p_total in sorted_projects:
if p_total == max_project_total:
results.append([
v_id,
village_by_id[v_id]["village_name"],
float(village_totals[v_id]),
proj["project_id"],
proj["project_name"],
float(p_total)
])
return results