LeetCode 196: Delete Duplicate Emails Solution

Master LeetCode problem 196 (Delete Duplicate Emails), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

196. Delete Duplicate Emails

Problem Explanation

Explanation:

To solve this problem, we need to delete all duplicate emails in the Person table, keeping only one unique email with the smallest id. We can achieve this by using a DELETE statement in SQL.

Algorithmic Idea:

  1. We can use a DELETE statement with a common table expression (CTE) to delete duplicate emails based on the condition of having a smaller id.
  2. The CTE can select the rows to delete by identifying duplicate emails with larger id values.
  3. We then delete the rows from the original Person table based on the CTE results.

Time Complexity:

The time complexity of this solution is O(n), where n is the number of rows in the Person table.

Space Complexity:

The space complexity is O(1) as we are not using any extra space apart from the input Person table itself.

:

Solution Code

// Java Solution
DELETE p
FROM Person p
JOIN (
    SELECT id, email
    FROM (
        SELECT id, email, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rnum
        FROM Person
    ) tmp
    WHERE rnum > 1
) dup ON p.id = dup.id;

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 196 (Delete Duplicate Emails)?

This page provides optimized solutions for LeetCode problem 196 (Delete Duplicate Emails) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 196 (Delete Duplicate Emails)?

The time complexity for LeetCode 196 (Delete Duplicate Emails) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 196 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 196 in Java, C++, or Python.

Back to LeetCode Solutions