Filter Hosts by Property Count, Rating, and Review Recency
SQL & DataAuto-graded · 16 test casesLast updated
Tests multi-table aggregation with date-windowed filtering, distinct counting, and host-level qualification across inventory, ratings, and coverage.
Problem Statement
You are analyzing property rental platform data to identify high-quality hosts. Write a function that finds all hosts satisfying all three of the following conditions:
- The host owns at least 2 active properties (where
is_active = True). - The host's overall average rating, computed across every review they have ever received on any of their properties (active or inactive), is at least 4.50 (before rounding).
- Every one of the host's active properties has received at least one review between
'2023-07-05'and'2024-01-01'(inclusive on both ends).
Input Format
listings: A list of dictionaries, each with:
listing_id(int): unique property identifierhost_id(int): owner identifieris_active(bool): whether the property is currently active
reviews: A list of dictionaries, each with:
review_id(int): unique review identifierlisting_id(int): the property being reviewed (may or may not exist inlistings)rating(float): guest rating, a value between 1.0 and 5.0review_date(str): date in ISO format"YYYY-MM-DD"
Output Format
Return a list of lists, where each inner list contains exactly three elements:
host_id(int)active_property_count(int): the number of active properties owned by this hostmean_rating(float): the overall average rating across all of the host's reviews, rounded to exactly 2 decimal places
Sort order: by mean_rating descending, then by host_id ascending (both applied to the rounded rating for sorting purposes).
Constraints
- 1 ≤ number of listings ≤ 10,000
- 0 ≤ number of reviews ≤ 100,000
- All
review_datestrings are valid ISO 8601 dates - All ratings are between 1.0 and 5.0 inclusive
- A property may have zero, one, or many reviews
- Reviews may reference
listing_idvalues not present inlistings(these reviews should be ignored) - The 180-day recency window is fixed: from
'2023-07-05'through'2024-01-01'inclusive
Example
Input:
listings = [
{"listing_id": 101, "host_id": 1, "is_active": True},
{"listing_id": 102, "host_id": 1, "is_active": True},
{"listing_id": 103, "host_id": 2, "is_active": True},
{"listing_id": 104, "host_id": 2, "is_active": True},
{"listing_id": 105, "host_id": 3, "is_active": True}
]
reviews = [
{"review_id": 1, "listing_id": 101, "rating": 4.8, "review_date": "2023-11-10"},
{"review_id": 2, "listing_id": 102, "rating": 4.6, "review_date": "2023-12-01"},
{"review_id": 3, "listing_id": 103, "rating": 4.9, "review_date": "2023-08-15"},
{"review_id": 4, "listing_id": 104, "rating": 4.7, "review_date": "2022-01-10"},
{"review_id": 5, "listing_id": 105, "rating": 5.0, "review_date": "2023-10-05"}
]
Output:
[[1, 2, 4.70]]
Explanation:
- Host 1: owns 2 active properties (101, 102). Overall average rating = (4.8 + 4.6) / 2 = 4.70 ≥ 4.50. Both active properties have reviews within the window (
2023-11-10and2023-12-01). All conditions met. ✓ - Host 2: owns 2 active properties (103, 104). Overall average rating = (4.9 + 4.7) / 2 = 4.80 ≥ 4.50. However, property 104's only review is dated
2022-01-10, which is outside the window. Only 1 out of 2 active properties (50%) has a recent review. Fails condition 3. ✗ - Host 3: owns only 1 active property (105). Fails condition 1 (need ≥ 2). ✗
Important Rules and Edge Cases
- Rating calculation scope: The average rating includes all reviews on all of the host's properties, regardless of whether those properties are currently active or inactive, and regardless of review date. Only conditions 1 and 3 are restricted to active properties.
- Recency coverage: An active property counts as "covered" if it has at least one review with
review_datebetween'2023-07-05'and'2024-01-01'inclusive. If a property has multiple reviews in the window, it still counts as one covered property (no double-counting). - Unreviewed properties: An active property with zero reviews ever fails condition 3 (it is not covered).
- Rating threshold: The 4.50 threshold is applied to the unrounded average. A host with an average of 4.495 does not qualify, even though rounding would display 4.50.
- Orphan reviews: Reviews with a
listing_idthat does not appear inlistingsare silently ignored. - Hosts with zero reviews: A host with no reviews at all cannot have an average rating ≥ 4.50 and should be excluded.
- Inactive properties: Do not count toward the active property count or coverage requirement, but their reviews do contribute to the overall average rating.
Examples
Example 1
Input: filter_qualified_hosts([{'listing_id': 101, 'host_id': 1, 'is_active': True}, {'listing_id': 102, 'host_id': 1, 'is_active': True}, {'listing_id': 103, 'host_id': 2, 'is_active': True}, {'listing_id': 104, 'host_id': 2, 'is_active': True}, {'listing_id': 105, 'host_id': 3, 'is_active': True}], [{'review_id': 1, 'listing_id': 101, 'rating': 4.8, 'review_date': '2023-11-10'}, {'review_id': 2, 'listing_id': 102, 'rating': 4.6, 'review_date': '2023-12-01'}, {'review_id': 3, 'listing_id': 103, 'rating': 4.9, 'review_date': '2023-08-15'}, {'review_id': 4, 'listing_id': 104, 'rating': 4.7, 'review_date': '2022-01-10'}, {'review_id': 5, 'listing_id': 105, 'rating': 5, 'review_date': '2023-10-05'}])
Output: [[1, 2, 4.7]]
Hints
Hint 1
Calculate the three conditions separately: count active properties per host, compute overall average ratings across all reviews, and track which active properties have at least one recent review.
Hint 2
Use a set to record which active properties have recent reviews, ensuring that multiple reviews on the same property don't inflate the coverage count.
Hint 3
Remember that the rating average includes reviews from all properties (active and inactive, any date), while the recency requirement only applies to active properties within the 180-day window.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires computing three distinct conditions that operate on different subsets of the data:
-
Active property count: Count how many active properties each host owns by iterating through
listingsand filtering whereis_active = True. -
Overall average rating: Accumulate the sum and count of all reviews for each host's properties (regardless of property status or review date), then compute the mean.
-
Recent review coverage: For each review, check if it references an active property and falls within the 180-day window (
2023-07-05to2024-01-01inclusive). Track which active properties have at least one such review using a set (to avoid double-counting properties with multiple recent reviews). A host qualifies only when the size of this set equals their active property count.
The critical insight is that these three calculations must be kept separate. The rating average uses all reviews ever received on any property, while the coverage requirement is restricted to active properties with recent reviews.
Implementation Steps
- Build a lookup dictionary mapping
listing_idto listing records for efficient joins. - Count active properties per host.
- Process all reviews:
- Accumulate rating sums and counts per host (all reviews).
- Track which active properties have reviews in the time window (using a set per host).
- For each host with at least 2 active properties:
- Check if they have any reviews (avoid division by zero).
- Compute the unrounded mean rating and verify it's ≥ 4.5.
- Check if the number of covered active properties equals the total active count.
- Sort by rounded rating descending, then by
host_idascending.
Why It Works
- Property lookup: The dictionary enables O(1) joins from reviews to properties.
- Deduplication: Using a set ensures properties with multiple recent reviews are counted only once toward coverage.
- Orphan handling: Reviews referencing non-existent properties are skipped via the
.get()check. - Floating-point precision: Adding
1e-12before rounding compensates for floating-point accumulation errors, ensuring results match exact decimal arithmetic. - Threshold comparison: The 4.5 threshold is checked against the unrounded average, so a value like 4.495 correctly fails.
Complexity
- Time: O(L + R + H log H), where L is the number of listings, R the number of reviews, and H the number of qualifying hosts. We scan each input once and sort only the result.
- Space: O(L + H) for the listing map, per-host accumulators, and coverage sets.
Full Solution
from collections import defaultdict
from datetime import date
from typing import Dict, List
def filter_qualified_hosts(listings: List[Dict], reviews: List[Dict]) -> List[List]:
window_start = date(2023, 7, 5)
window_end = date(2024, 1, 1)
listing_map = {listing["listing_id"]: listing for listing in listings}
active_counts = defaultdict(int)
recent_coverage = defaultdict(set)
rating_sums = defaultdict(float)
rating_counts = defaultdict(int)
for listing in listings:
if listing["is_active"]:
active_counts[listing["host_id"]] += 1
for review in reviews:
listing = listing_map.get(review["listing_id"])
if listing is None:
continue
host_id = listing["host_id"]
rating_sums[host_id] += review["rating"]
rating_counts[host_id] += 1
review_dt = date.fromisoformat(review["review_date"])
if listing["is_active"] and window_start <= review_dt <= window_end:
recent_coverage[host_id].add(listing["listing_id"])
result = []
for host_id, active_count in active_counts.items():
if active_count < 2 or rating_counts[host_id] == 0:
continue
mean_rating = rating_sums[host_id] / rating_counts[host_id]
covered_count = len(recent_coverage[host_id])
if mean_rating >= 4.5 and covered_count == active_count:
result.append([host_id, active_count, round(mean_rating + 1e-12, 2)])
result.sort(key=lambda row: (-row[2], row[0]))
return result