The Find Expensive Cities interview question is a database management task that requires analyzing price data across different geographical locations. You are typically given a table containing listings of properties or products with their associated prices and the city they belong to. Your goal is to identify cities where the average price of all items is higher than the overall national (or global) average price. The output should be a list of these "expensive" cities, often sorted alphabetically or by the price difference.
Companies like Google ask this Find Expensive Cities coding problem to evaluate a candidate's proficiency in SQL aggregation and subqueries. It tests your ability to calculate a summary statistic (the global average) and then use that statistic as a filter for grouped data. This is a fundamental skill for data analysis, backend engineering, and business intelligence roles, where identifying outliers or top-performing segments is a common requirement.
This problem follows the Database, Aggregation, and Subquery interview pattern. The standard approach involves:
AVG() price across the entire dataset.city using the GROUP BY clause.AVG() price per city.HAVING clause to compare the city average against the result of the global average subquery.Imagine a table Listings:
Step-by-step:
WHERE clause instead of HAVING. Remember, WHERE filters rows before grouping, while HAVING filters results after aggregation.SELECT for every row instead of calculating it once as a standalone scalar value.NULL values in the price column, which can skew averages.Practice using Window Functions like AVG() OVER() as an alternative to subqueries. While a subquery is more traditional, window functions can sometimes be more readable and performant in complex analytical queries.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Calculate Compressed Mean | Easy | Solve | |
| Calculate Special Bonus | Easy | Solve | |
| Find Customers With Positive Revenue this Year | Easy | Solve | |
| Loan Types | Easy | Solve | |
| The Latest Login in 2020 | Easy | Solve |