↓Skip to main content
  1. LeetCode/

LeetCode 182: Duplicate Emails

·1 min· ·
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: Accepted (first try)

Approach
#

“Appears more than once” is a condition on groups, so use GROUP BY email with HAVING COUNT(*) > 1 (SQL Template 4). WHERE filters single rows before grouping and cannot use aggregates.

My Attempts
#

Passed on the first try with GROUP BY and HAVING count(Email) > 1.

Solution
#

SELECT email AS Email
FROM Person
GROUP BY email
HAVING COUNT(*) > 1;

Complexity
#

Grouping is O(n) by hashing or O(n log n) by sorting.

Mistakes to Avoid
#

  • Aggregate conditions go in HAVING, not WHERE.

Interview Explanation
#

I group by email and keep groups with a count above one using HAVING, since aggregate conditions belong there rather than in WHERE.

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 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 196: Delete Duplicate Emails
·2 mins
LeetCode Easy Database
LeetCode 196 note: it must be a DELETE, not a SELECT; keep only the smallest id per email and delete the rest
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