Rank Advertisers by Reports, Then Report Rate
Heaps, Sorting & SearchAuto-graded · 17 test casesLast updated
Aggregate per-ad records by advertiser, then rank with a multi-key sort (total reports, report rate, id) and return the top k.
A trust-and-safety team keeps one record per advertisement. Each record says which advertiser owns the ad, how many people visited the ad's page, and how many of those people flagged the ad as harmful. You need to find the advertisers who look the worst.
Task
Implement a function that takes a list of ad records and an integer k, and returns the ids of the k worst advertisers, worst first.
Each record is a dictionary with these keys:
"advertiser_id": a string identifying the advertiser."page_visits": a non-negative integer, the visits to this ad's page."bad_reports": a non-negative integer, the number of reports filed against this ad.
An advertiser may own many ads, so the same advertiser_id can appear in several records.
Scoring rules
- Combine per advertiser. For each advertiser, add up
bad_reportsover all of their records to gettotal_reports. Do the same forpage_visitsto gettotal_visits. - Report rate.
report_rate = total_reports / total_visits. Iftotal_visitsis0, the rate is defined as0. - Ordering. Rank advertisers by these keys in order:
- Larger
total_reportsfirst. - If tied, larger
report_ratefirst. - If still tied,
advertiser_idin ascending (lexicographic) order.
- Larger
Compute the rate with ordinary true (floating-point) division and compare the resulting values.
Output
Return a list of the first k advertiser ids in this order.
- If
kis larger than the number of distinct advertisers, return all of them. - If
k <= 0, return an empty list. - Advertisers with zero reports are still ranked, so they appear after everyone with more reports.
Constraints
0 <= len(records) <= 10^5page_visitsandbad_reportsare integers>= 0kis an integer and may be zero, negative, or larger than the number of advertisers- Each record contains all three keys
- Advertiser ids are non-empty strings
Examples
Example 1
Input: rank_flagged_advertisers([{'advertiser_id': 'a1', 'page_visits': 1000, 'bad_reports': 80}, {'advertiser_id': 'a2', 'page_visits': 100, 'bad_reports': 30}, {'advertiser_id': 'a1', 'page_visits': 500, 'bad_reports': 20}, {'advertiser_id': 'a3', 'page_visits': 50, 'bad_reports': 30}], 2)
Output: ['a1', 'a3']
Example 2
Input: rank_flagged_advertisers([{'advertiser_id': 'shop_x', 'page_visits': 10, 'bad_reports': 0}, {'advertiser_id': 'shop_y', 'page_visits': 10, 'bad_reports': 2}, {'advertiser_id': 'shop_z', 'page_visits': 1000, 'bad_reports': 2}], 3)
Output: ['shop_y', 'shop_z', 'shop_x']
Hints
Hint 1
Group the records by advertiser first. A dictionary that holds running totals of reports and visits per advertiser is enough.
Hint 2
Compute the rate only after summing across all of an advertiser's records, and guard against a total of zero visits.
Hint 3
Sort with a key tuple. Negate the numeric fields so they sort descending while the advertiser id stays ascending, then slice off the first k.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Walk through the records once and keep a dictionary mapping each advertiser to
[total_reports, total_visits]. This merges all ads owned by the same advertiser. - For each advertiser, compute the report rate as
total_reports / total_visits, using0when there are no visits. - Sort the advertisers with the key
(-total_reports, -report_rate, advertiser_id). Negating the numeric parts gives descending order for them, while the id stays in natural ascending order, so the final order is fully deterministic. - Return the first
kids. Slicing handlesklarger than the number of advertisers. A non-positivekreturns an empty list immediately.
Why it is correct
- The rate is computed from summed totals, so it is weighted by visits. Averaging per-ad rates would let a tiny ad count as much as a huge one, which is not what the task asks for.
- The key tuple encodes the three ranking rules in priority order. Python compares tuples element by element, so the rate only matters when report totals are equal, and the id only matters when both are equal.
- The zero-visit rule avoids division by zero.
Complexity
- Time:
O(n + m log m), wherenis the number of records andmthe number of distinct advertisers. - Space:
O(m)for the totals.
Reference solution
from typing import List, Dict
def rank_flagged_advertisers(records: List[Dict], k: int) -> List[str]:
if k <= 0:
return []
totals = {}
for rec in records:
adv = rec["advertiser_id"]
if adv not in totals:
totals[adv] = [0, 0]
totals[adv][0] += rec["bad_reports"]
totals[adv][1] += rec["page_visits"]
def sort_key(item):
adv, (reports, visits) = item
rate = reports / visits if visits else 0.0
return (-reports, -rate, adv)
ordered = sorted(totals.items(), key=sort_key)
return [adv for adv, _ in ordered[:k]]