Grouped Median Property Price by Region
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Tests ability to compute per-group medians over a list of records, correctly handling odd/even counts, duplicate values, and half-up rounding to two decimal places.
Problem
You are given a collection of property listings, each tagged with a region name and an asking price. Your task is to find the median asking price for every region and return the results in alphabetical order by region name.
The median is defined as follows:
- Sort all prices within a region in ascending order.
- If the region has an odd number of listings, the median is the single middle price.
- If the region has an even number of listings, the median is the arithmetic mean of the two middle prices.
Round every median to two decimal places, using half-up rounding (0.005 rounds to 0.01).
Input
A list of dictionaries. Each dictionary represents one listing and contains:
| Key | Type | Description |
|---|---|---|
"id" | int | Unique listing identifier |
"city" | str | Region name (non-null) |
"price" | int or float | Asking price (positive, non-null) |
Output
A list of dictionaries, one per region, sorted alphabetically by "city". Each dictionary contains:
| Key | Type | Description |
|---|---|---|
"city" | str | Region name |
"median_price" | float | Median price rounded to two decimal places |
Constraints
- The input list has between 1 and 10^6 entries.
- Every region contains at least one listing.
priceis a positive number; it will not be zero or negative.- Do not deduplicate prices. If a region has three listings all priced at 100, the median is 100.
- Prices may have up to two decimal places (e.g.,
10.01). - When two middle prices average to a value ending in exactly 0.005, round up (away from zero) to the nearest cent.
- Return regions in ascending lexicographic order by
"city".
Examples
Example 1
Input: median_house_price([{'id': 1, 'city': 'Austin', 'price': 100}, {'id': 2, 'city': 'Austin', 'price': 200}, {'id': 3, 'city': 'Austin', 'price': 300}, {'id': 4, 'city': 'Austin', 'price': 400}, {'id': 5, 'city': 'San Francisco', 'price': 150}, {'id': 6, 'city': 'San Francisco', 'price': 250}, {'id': 7, 'city': 'San Francisco', 'price': 350}, {'id': 8, 'city': 'Seattle', 'price': 500}])
Output: [{'city': 'Austin', 'median_price': 250}, {'city': 'San Francisco', 'median_price': 250}, {'city': 'Seattle', 'median_price': 500}]
Example 2
Input: median_house_price([{'id': 1, 'city': 'Boston', 'price': 100}, {'id': 2, 'city': 'Boston', 'price': 100}, {'id': 3, 'city': 'Boston', 'price': 125}, {'id': 4, 'city': 'Chicago', 'price': 80}])
Output: [{'city': 'Boston', 'median_price': 100}, {'city': 'Chicago', 'median_price': 80}]
Example 3
Input: median_house_price([{'id': 1, 'city': 'New York', 'price': 10.01}, {'id': 2, 'city': 'New York', 'price': 10.02}, {'id': 3, 'city': 'New York', 'price': 10.03}, {'id': 4, 'city': 'New York', 'price': 10.04}])
Output: [{'city': 'New York', 'median_price': 10.03}]
Hints
Hint 1
Group all prices by region name first, then sort each group independently — you only need order statistics within a group, not a global sort.
Hint 2
For a group of size n, the middle index (1-based) is n//2 for odd n. For even n, you need the average of the elements at 0-based indices n//2 - 1 and n//2 after sorting.
Hint 3
Python's built-in round() uses banker's rounding, which can give wrong results for exact half-cent values. Use the Decimal module with ROUND_HALF_UP to match the expected output precisely.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is computing an order statistic (the median) independently for each group, then rounding correctly.
Step 1 — Group by region. Iterate through the input once and collect each listing's price into a dictionary keyed by city name. This is O(N) and keeps the rest of the work local to each group.
Step 2 — Sort each group and locate the middle.
For a group of size n, sort its prices in ascending order (O(n log n)). The median position depends on parity:
| n | middle index (0-based) | formula |
|---|---|---|
| odd | single middle | prices[n // 2] |
| even | average of two middles | (prices[n//2 - 1] + prices[n//2]) / 2 |
This matches the problem's definition exactly. Duplicates are left in place, so the sort positions them naturally without any deduplication step.
Step 3 — Exact decimal arithmetic.
Convert each price to Decimal(str(price)) before any arithmetic. Going through the string representation avoids the binary floating-point representation error that affects values like 0.1 or 10.01. Dividing by Decimal(2) keeps the result exact.
Step 4 — Half-up rounding.
.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) rounds the result to two decimal places, rounding a trailing 5 upward. Python's built-in round() uses banker's rounding (half-to-even), which would give wrong answers for inputs like (10.01 + 10.02) / 2 = 10.015.
Step 5 — Alphabetical output.
Iterating over sorted(prices_by_city) produces region names in ascending lexicographic order, satisfying the output requirement without a separate sort pass.
Why this is correct for every edge case:
- Single listing:
n = 1, odd branch,prices[0]is returned — correct. - All duplicates: e.g.,
[100, 100, 100]→ middle is100— no deduplication occurs. - Half-cent average: e.g.,
(10.02 + 10.03) / 2 = 10.025→ rounds to10.03with ROUND_HALF_UP.
Complexity
- Time: O(N log N) overall. Each price is visited once during grouping, and sorting within each group of size n_c costs O(n_c log n_c). The sum across all groups is bounded by N log N.
- Space: O(N) to store all prices in the grouping dictionary.
Reference Solution
from collections import defaultdict
from decimal import Decimal, ROUND_HALF_UP
from typing import List, Dict
def median_house_price(rows: List[Dict[str, object]]) -> List[Dict[str, object]]:
# Group prices by region, converting each price to Decimal immediately
# to avoid floating-point accumulation errors during arithmetic.
prices_by_city = defaultdict(list)
for row in rows:
prices_by_city[row["city"]].append(Decimal(str(row["price"])))
result = []
for city in sorted(prices_by_city):
prices = sorted(prices_by_city[city])
n = len(prices)
if n % 2:
# Odd count: the middle element sits at index n // 2
median = prices[n // 2]
else:
# Even count: average the two middle elements
median = (prices[n // 2 - 1] + prices[n // 2]) / Decimal(2)
# Round to two decimal places with half-up semantics
median = median.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
result.append({"city": city, "median_price": float(median)})
return result