0182 - Duplicate Emails (Easy)
Problem Link
https://leetcode.com/problems/duplicate-emails
Problem Statement
Table: Person
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| email | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.Write a solution to report all the duplicate emails. Note that it's guaranteed that the email field is not NULL.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Person table:
+----+---------+
| id | email |
+----+---------+
| 1 | a@b.com |
| 2 | c@d.com |
| 3 | a@b.com |
+----+---------+
Output:
+---------+
| Email |
+---------+
| a@b.com |
+---------+
Explanation: a@b.com is repeated two times.Approach 1: GROUP BY + HAVING
The idea is to group the rows by their email value, then keep only the groups that contain more than one row, i.e those are the duplicates.
GROUP BY emailcollapses all rows that share the same email into a single group. For the example input, this creates two groups: one fora@b.com(containing rows withid1 and 3) and one forc@d.com(containing the row withid2).COUNT(*)computes how many rows fall into each group. Here,a@b.comhas a count of2andc@d.comhas a count of1.HAVING COUNT(*) > 1filters the groups after aggregation, keeping only those whose row count is at least 2. We useHAVINGinstead ofWHEREbecauseWHEREfilters individual rows before grouping and cannot reference aggregate functions likeCOUNT(*).
Time complexity: on average, where is the number of rows in Person, since each row is scanned once to build the groups (hash-based grouping). With sort-based grouping it may be .
Space complexity: , where is the number of distinct emails for storing the group aggregates.
SELECT email FROM Person
GROUP BY email
HAVING COUNT(*) > 1