Find Valid Emails Problem
#3436
Description
LeetCode Problem 3436.
Table: Users
+-----------------+---------+
| Column Name | Type |
+-----------------+---------+
| user_id | int |
| email | varchar |
+-----------------+---------+
(user_id) is the unique key for this table.
Each row contains a user's unique ID and email address.
Write a solution to find all the valid email addresses. A valid email address meets the following criteria:
- It contains exactly one
@symbol. - It ends with
.com. - The part before the
@symbol contains only alphanumeric characters and underscores. - The part after the
@symbol and before.comcontains a domain name that contains only letters.
Return the result table ordered by user_id in ascending order.
Example:
Input:
Users table:
+---------+---------------------+
| user_id | email |
+---------+---------------------+
| 1 | [email protected] |
| 2 | bob_at_example.com |
| 3 | [email protected] |
| 4 | [email protected] |
| 5 | eve@invalid |
+---------+---------------------+
Output:
+---------+-------------------+
| user_id | email |
+---------+-------------------+
| 1 | [email protected] |
| 4 | [email protected] |
+---------+-------------------+
Explanation:
- [email protected] is valid because it contains one @, alice is alphanumeric, and example.com starts with a letter and ends with .com.
- bob_at_example.com is invalid because it contains an underscore instead of an @.
- [email protected] is invalid because the domain does not end with .com.
- [email protected] is valid because it meets all criteria.
- eve@invalid is invalid because the domain does not end with .com.
Result table is ordered by user_id in ascending order.
Solution
Approach: One anchored regular expression
All four rules can be written as one pattern that has to match the whole address:
^[A-Za-z0-9_]+@[A-Za-z]+\.com$
^[A-Za-z0-9_]+is the local part: one or more letters, digits or underscores. It cannot contain a second@or any other symbol, and it cannot be empty.@is the single separator. Since the characters on both sides are restricted and contain no@, there is exactly one.[A-Za-z]+is the domain name, letters only (soexa-mpleorex1is rejected).\.com$requires the literal.comat the very end. The dot is escaped, otherwise it would match any character andxcomwould pass. In a MySQL string literal the backslash itself has to be doubled, hence\\.com.
The anchors ^ and $ matter: without them a valid-looking piece in the middle of a longer string would count. In Pandas, str.fullmatch is the same as anchoring both ends.
SELECT user_id, email
FROM Users
WHERE email REGEXP '^[A-Za-z0-9_]+@[A-Za-z]+\\.com$'
ORDER BY user_id;