Problem
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.com
contains a domain name that contains only letters.
Return the result table ordered by user_id
in ascending order.
Example 1:
|
|
Example 2:
Solution
Method 1 – Regex Filtering
Intuition
We use a regular expression to match emails that satisfy all the given criteria: exactly one @
, ends with .com
, valid username (alphanumeric/underscore), and valid domain (letters only).
Approach
- Use a regex to match emails with:
- One
@
symbol. - Ends with
.com
. - Username (before
@
) contains only alphanumeric or underscores. - Domain (after
@
and before.com
) contains only letters.
- One
- Filter the Users table using this regex.
- Return the user_id and email, ordered by user_id ascending.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N)
, where N is the number of users, since we check each email once. - 🧺 Space complexity:
O(N)
, for storing the filtered result.