↓Skip to main content
  1. LeetCode/

LeetCode 196: Delete Duplicate Emails

·2 mins· ·
LeetCode Easy Database
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2021-10-09

  • Submissions: Wrong Answer ×2 → Accepted

Approach
#

The problem asks to modify the table, so this is a DELETE of every row whose id is not the smallest for its email. Two ways:

  • A NOT IN subquery keeping each group’s MIN(id) (SQL Template 4); MySQL forbids a DELETE subquery from reading the same table directly, so wrap it in a derived table.
  • MySQL’s self-join form: DELETE p1 FROM Person p1 JOIN Person p2 ON p1.email = p2.email AND p1.id > p2.id (SQL Template 3).

My Attempts
#

The first two were SELECTs: SELECT DISTINCT(Email), then a self join selecting the rows to remove, but the task requires actually deleting them, and a SELECT leaves the table unchanged. Turning the same condition into DELETE p1 FROM ... passed.

Solution
#

DELETE FROM Person
WHERE id NOT IN (
    SELECT id FROM (SELECT MIN(id) AS id FROM Person GROUP BY email) AS keep
);

Complexity
#

Grouping in O(n) or O(n log n), then deleting.

Mistakes to Avoid
#

  • The task deletes data; a SELECT changes nothing.
  • MySQL DELETE subqueries cannot read the same table directly; wrap them once more.

Interview Explanation
#

The table itself must change, so I DELETE every row except the smallest id per email, found by grouping in a subquery wrapped in a derived table because MySQL forbids reading the target table directly; a self-join DELETE of the larger ids also works.

Related

LeetCode 175: Combine Two Tables
·1 min
LeetCode Easy Database
LeetCode 175 note: people without an address must still appear, so LEFT JOIN, leaving city and state NULL when unmatched
LeetCode 181: Employees Earning More Than Their Managers
·1 min
LeetCode Easy Database
LeetCode 181 note: self-join Employee on managerId = id to pair employees with managers, then compare salaries
LeetCode 182: Duplicate Emails
·1 min
LeetCode Easy Database
LeetCode 182 note: group by email and keep groups with HAVING COUNT(*) > 1
LeetCode 183: Customers Who Never Order
·1 min
LeetCode Easy Database
LeetCode 183 note: LEFT JOIN Orders, and customers with no matching order (o.id IS NULL) never ordered; NOT IN also works
LeetCode 26: Remove Duplicates from Sorted Array
·2 mins
LeetCode Easy Array Two-Pointers
LeetCode 26 note: overwrite in place with a write pointer for the next slot, writing only values different from the last one written
LeetCode 14: Longest Common Prefix
·2 mins
LeetCode Easy Array String Trie
LeetCode 14 note: bound by the shortest string and check each position across all strings; the first mismatch gives the answer’s length