Impression-Weighted Median CTR of Ads in Each Country

Last updated: November 29, 2026

Quick Overview

Given per-ad impressions and clicks by country, compute each country's impression-weighted median CTR: the CTR of the ad at which cumulative impressions, sorted by CTR, first reach half of the country's total impressions.

Meta
Data Manipulation (SQL/Python)
Data Scientist
Meta
November 29, 2026
Data Scientist
Onsite
Data Manipulation (SQL/Python)
Hard

0

0

0 solved


Given per-ad impressions and clicks by country, compute each country's impression-weighted median CTR: the CTR of the ad at which cumulative impressions, sorted by CTR, first reach half of the country's total impressions.

Ads quality reviews at Meta compare typical CTR across markets, and a plain median over ads lets tiny ads dominate. The interviewer wants a weighted percentile built from a running sum over a sorted partition, with a careful threshold rule and tie-break.

What the Interviewer Expects
  • Computes CTR per ad and drops ads with zero impressions
  • Sorts by CTR within country with a deterministic tie-break
  • Builds cumulative impressions with a ROWS frame and a country total with an unframed window
  • Selects the first ad where cumulative impressions reach half the total
  • Explains why the weighted median differs from both the plain median and the pooled CTR
Key Topics to Cover
weighted median
running SUM
threshold selection
PARTITION BY
robust statistics
How to Approach This
  1. Clarify the schema and expected output format before writing queries.
  2. Use CTEs (WITH clauses) to break complex queries into readable steps.
  3. Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
  4. Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
  5. For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
  • How would you generalize the query to any weighted percentile, such as p90?
  • When is pooled CTR (total clicks over total impressions) the better summary?
  • How would you add a bootstrap confidence interval for this statistic?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice SQL Problems
Sample Answer
Clarify the Data

Table: ad_country_stats(country, ad_id, impressions, clicks) for one week. Each ad's CTR is clicks / impressions. I weight each ad by its impressions, so the statistic answers: 'what CTR does the ty...

Approach

Within each country, sort ads by CTR ascending. Running-sum impressions; the weighted median is the CTR of the first row where 2 * cum_impressions >= total_impressions. Because window results cannot...


Submit Your Answer
Markdown supported