EasyNo. 0196

Delete Duplicate Emails — LeetCode 196 Python Solution

Topics
Database
Reading time
2 min

The problem

Delete the duplicate rows so that only the row with the smallest id survives for each email address, leaving every other row untouched. The Person table has id (int, primary key) and email (varchar), and the addresses never contain uppercase letters. The answer changes the table in place rather than returning a result set.

Example

Input
Person(id, email) = (1, 'ana@example.com'), (2, 'ben@example.com'), (3, 'ana@example.com'), (4, 'ana@example.com')
Output
Person(id, email) = (1, 'ana@example.com'), (2, 'ben@example.com')
Explanation
Ids 3 and 4 duplicate an address already held by id 1, so only the smallest id per address survives.

Python solution

PythonSolution
import pandas as pd


# Modify Person in place
def delete_duplicate_emails(person: pd.DataFrame) -> None:
    # Sort the rows based on id (Ascending order)
    person.sort_values(by="id", ascending=True, inplace=True)
    # Drop the duplicates based on email.
    person.drop_duplicates(subset="email", keep="first", inplace=True)

Complexity

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0197Rising TemperatureEasy
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium

Frequently asked questions

How hard is LeetCode 196. Delete Duplicate Emails?

LeetCode 196. Delete Duplicate Emails is rated Easy on LeetCode.

What topics does LeetCode 196. Delete Duplicate Emails cover?

LeetCode 196. Delete Duplicate Emails is tagged Database on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.