MySQL 0585.sql
WITH uniq AS (SELECT lat, lon
FROM Insurance
GROUP BY lat, lon
HAVING COUNT(*) = 1),
same AS (SELECT tiv_2015
FROM Insurance
GROUP BY tiv_2015
HAVING COUNT(*) > 1)
SELECT ROUND(SUM(tiv_2016), 2) AS tiv_2016
FROM Insurance i, uniq u, same s
WHERE i.tiv_2015 = s.tiv_2015
AND i.lat = u.lat
AND i.lon = u.lon
Difficulty
and has an acceptance rate of about 52% (600k+ submissions).
Typical patterns to solve this problem:
- Database
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The script is a single-statement query that aggregates the 2016 total insured value (tiv_2016) from the Insurance table, but only for rows that satisfy two distinct uniqueness constraints. The first constraint isolates geographic points (latitude/longitude) that occur exactly once in the dataset. The second constraint isolates policy values from 2015 (tiv_2015) that appear in more than one record. By intersecting these two filtered sets, the query returns the rounded sum of tiv_2016 for the qualifying records.
Key Steps
Defining unique geographic locations
The first common table expression, named uniq, groups rows by latitude and longitude and retains only those groups whose count equals one. This step eliminates any coordinate that is shared by multiple policies, ensuring that only singular locations are considered later.
WITH uniq AS (
SELECT lat, lon
FROM Insurance
GROUP BY lat, lon
HAVING COUNT(*) = 1
)
Identifying duplicated 2015 values
The second common table expression, same, groups rows by the 2015 insured value and keeps only those groups whose count exceeds one. This filters for policy values that are not unique, i.e., values that appear in at least two different records.
, same AS (
SELECT tiv_2015
FROM Insurance
GROUP BY tiv_2015
HAVING COUNT(*) > 1
)
Joining the filtered sets and aggregating
The main SELECT statement joins the original Insurance table with the two CTEs using inner joins expressed in the legacy comma syntax. The join predicates enforce that a row from Insurance must match a unique latitude/longitude pair from uniq and a duplicated tiv_2015 value from same. After the join, the query computes the sum of tiv_2016 across all matching rows, rounds the result to two decimal places, and returns it as a single scalar column.
SELECT ROUND(SUM(tiv_2016), 2) AS tiv_2016
FROM Insurance i, uniq u, same s
WHERE i.tiv_2015 = s.tiv_2015
AND i.lat = u.lat
AND i.lon = u.lon
Edge Cases Handled
The use of HAVING COUNT(*) = 1 in uniq automatically excludes any latitude/longitude pair that is missing from the table (count zero) as well as any pair that appears multiple times. Consequently, rows with null latitude or longitude values are filtered out because a null group would not satisfy the equality condition in the join, and the count for a null group would not meet the exact-one requirement.
Similarly, HAVING COUNT(*) > 1 in same guarantees that a tiv_2015 value must be present in at least two rows to be considered. This eliminates solitary entries and also prevents the inclusion of rows where tiv_2015 is null, because a null group would not satisfy the count condition and would not join on the equality predicate.
The final WHERE clause combines both filters, so a row is selected only when it simultaneously belongs to a unique geographic point and a duplicated 2015 value. This logical conjunction inherently handles the case where a row meets one condition but not the other, ensuring it is excluded from the aggregation.
Performance Optimizations
The query leverages early reduction of the data set through the two CTEs. By grouping and applying HAVING clauses before the join, the engine can materialize relatively small intermediate result sets-one containing distinct latitude/longitude pairs and another containing duplicated tiv_2015 values. Joining these reduced sets to the main table limits the number of rows that participate in the final aggregation, which can significantly lower I/O and CPU consumption compared with scanning the entire Insurance table for each condition.
If appropriate indexes exist on the columns used in grouping (lat, lon, tiv_2015) and on the join predicates, the database optimizer can perform index-only scans for the CTEs and use index lookups for the join, further reducing the amount of data read. The aggregation (SUM) operates on a narrowed subset, and the ROUND function is applied after the sum, avoiding repeated rounding operations on intermediate rows.
Overall, the structure of the query-filter-first, join-later, aggregate-last-aligns with common optimization patterns that minimize the volume of data processed at each stage.
ELI5 - Simplified Explanation
Imagine there is a big collection of building insurance cards scattered on the floor. Each card has a special address spot marked by its latitude and longitude. Some cards sit all by themselves in their own part of town, while other cards are forced to share the same spot in town with many neighbors.
The first part of the project finds the special loners. It looks at all the addresses and picks out only the ones where there is just a single house standing there. Those are the houses that do not have to share their space.
The second part of the project looks for crowds. These are the insurance cards that share the exact same financial value as other cards in the pile. It keeps track of these popular values that appear more than once.
Finally, the code puts everything together. It looks through all the houses again to see which ones are the loners that also have a popular financial value. Once the houses that fit these two rules are found, the code adds up all their values from the second year to see the final total.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||
|---|---|---|---|---|---|---|
| author | solutions | |||||
| www | AlgoMonster | C++ | Java | Python | TS | |
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| LeetcodeHelp | C++ | Java | Python | |||
| Progiez | C++ | Java | Python | |||
| github | everthis | SQL | ||||
| suxrobGM | SQL | |||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| LeetcodeHelp | C++, Java, Python | |||||
| Progiez | C++, Java, Python | |||||
| everthis | SQL | |||||
| suxrobGM | SQL |
Videos
Solved On The Same Day
- problem 175: Combine Two Tables
- problem 181: Employees Earning More Than Their Managers
- problem 182: Duplicate Emails
- problem 183: Customers Who Never Order
- problem 193: Valid Phone Numbers
- problem 196: Delete Duplicate Emails
- problem 197: Rising Temperature
- problem 203: Remove Linked List Elements
- problem 511: Game Play Analysis I
- problem 577: Employee Bonus
- problem 584: Find Customer Referee
- problem 586: Customer Placing the Largest Number of Orders
- problem 595: Big Countries
- problem 596: Classes With at Least 5 Students
- problem 607: Sales Person
- problem 610: Triangle Judgement
- problem 619: Biggest Single Number
- problem 620: Not Boring Movies
- problem 627: Swap Sex of Employees
- problem 1050: Actors and Directors Who Cooperated At Least Three Times
- problem 1068: Product Sales Analysis I
- problem 1075: Project Employees I
- problem 1084: Sales Analysis III
- problem 1141: User Activity for the Past 30 Days I
- problem 1148: Article Views I
- problem 1179: Reformat Department Table
- problem 176: Second Highest Salary
- problem 177: Nth Highest Salary
- problem 178: Rank Scores
- problem 180: Consecutive Numbers
- problem 184: Department Highest Salary
- problem 192: Word Frequency
- problem 194: Transpose File
- problem 550: Game Play Analysis IV
- problem 570: Managers with at Least 5 Direct Reports
- problem 602: Friend Requests II: Who Has the Most Friends
- problem 608: Tree Node
- problem 626: Exchange Seats
- problem 725: Split Linked List in Parts
- problem 1045: Customers Who Bought All Products
- problem 1070: Product Sales Analysis III
- problem 1164: Product Price at a Given Date
- problem 1174: Immediate Food Delivery II
- problem 1193: Monthly Transactions I
- problem 1204: Last Person to Fit in the Bus
- problem 1321: Restaurant Growth
- problem 1393: Capital Gain/Loss
- problem 174: Dungeon Game
- problem 185: Department Top Three Salaries
- problem 218: The Skyline Problem
- problem 262: Trips and Users
- problem 601: Human Traffic of Stadium
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality