Find Valid Emails solution and explanation
3 more videos on this problem
Leetcode 3436 - Regular Expressions (RegEx) in SQL - Find Valid Emails | Everyday Data ScienceEveryday Data Science · 5:56 · 970 views
LeetCode 3436: Find Valid Emailsmatjazcodes · 3:31 · 62 views
Leetcode 3436 Find Valid EmailsAlgorithmicIQ · 6:27 · 49 views
SQL vs Pandas: Which is better for Data Interviews? (LeetCode 3436)DataHead Girl · 6:29 · 48 views
The 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.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 | alice@example.com | | 2 | bob_at_example.com | | 3 | charlie@example.net | | 4 | david@domain.com | | 5 | eve@invalid | +---------+---------------------+
Output:
+---------+-------------------+ | user_id | email | +---------+-------------------+ | 1 | alice@example.com | | 4 | david@domain.com | +---------+-------------------+
Explanation:
- alice@example.com 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
@. - charlie@example.net is invalid because the domain does not end with
.com. - david@domain.com 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.
Approach overview
Problem Overview: The Users table has a user_id and an email column. Return the rows whose email has a valid prefix followed by the exact domain @leetcode.com. The prefix must start with a letter and can contain only letters, digits, underscores, periods, and dashes. Sort the result by user_id.
Approach 1: Manual String Checks (O(n * L) time, O(L) space)
Split each email on the @ character, then confirm the domain equals leetcode.com exactly. Scan the prefix one character at a time and check that the first character is a letter and every remaining character belongs to the allowed set. This works in Pandas with a row-wise apply, and it makes each rule explicit. Prefer it when you need readable logic to debug or extend, since each rule maps to one check. Here n is the number of rows and L is the average email length.
Approach 2: Regular Expression (O(n * L) time, O(1) extra space)
Encode the full rule as one pattern: ^[A-Za-z][A-Za-z0-9_.-]*@leetcode\.com$. The anchors ^ and $ force a full match, so partial matches like abc@leetcode.com.evil fail. The database engine or Pandas evaluates the pattern in a single pass per row, and no intermediate strings are created. In MySQL, use WHERE email REGEXP '...'. In Pandas, use str.match with the same pattern. This is the approach to use in production and in interviews.
Recommended for interviews: Interviewers expect the regex approach, and they want you to justify each part of the pattern. Mention the anchors, the escaped dot in the domain, and the rule that the prefix must start with a letter. The manual check shows you understand the constraints. The regex shows you can express them concisely and correctly. Review database problems and string problems to practice this pattern.
Solution
Thinking
The statement fixes the email shape: the local part is alphanumerics and underscores; the domain starts with a letter and ends with
.com. Manual splits miss edge cases.A fully anchored regular expression enforces both ends and the character classes at once.
We keep rows matching
^[A-Za-z0-9_]+@[A-Za-z]+\.com<code>and sort by user_id.
We can use a regular expression with REGEXP to match valid email addresses.
The time complexity is O(n), and the space complexity is O(1). Here, n$ is the length of the input string.
# Write your MySQL query statement below
SELECT user_id, email
FROM Users
WHERE email REGEXP '^[A-Za-z0-9_]+@[A-Za-z]+\\.com$'
ORDER BY 1;import pandas as pd
def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
email_pattern = r"^[A-Za-z0-9_]+@[A-Za-z]+\.com$"
valid_emails = users[users["email"].str.match(email_pattern)]
valid_emails = valid_emails.sort_values(by="user_id")
return valid_emailsComplexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Manual String Checks | O(n * L) | O(L) | Rules change often or need step-by-step debugging |
| Regular Expression | O(n * L) | O(1) extra | General case in SQL or Pandas, and interview answers |
Frequently asked questions
Find Valid Emails Python solution
Use pandas: filter the DataFrame with df[df['email'].str.match(r'^[A-Za-z][A-Za-z0-9_.-]*@leetcode\\.com$')] and then select user_id and email, sorted by user_id. The regex enforces the prefix rules and the exact domain in one step.
Is Find Valid Emails easy or hard?
The problem is rated Easy with a 44.1 percent acceptance rate. The core challenge is writing a correct regex that enforces the prefix start rule and the exact domain. Once the pattern is clear, the query is a single WHERE clause.
How to solve Find Valid Emails in O(n)?
Treat each row as a constant-time check when emails are short, then apply a single regex filter across the table. The regex engine reads each character once per row, so the work scales linearly with the number of rows. Finish by ordering the result by user_id.
What is the best approach for Find Valid Emails?
The best approach is a regular expression that matches the full email in one pass. Use the pattern ^[A-Za-z][A-Za-z0-9_.-]*@leetcode\\.com$ with REGEXP in MySQL or str.match in Pandas. The anchors ensure the entire string matches, not just a substring.
What data structure is used in Find Valid Emails?
No dedicated data structure is needed. The solution works on a table of rows and relies on the regex engine's finite automaton to match each email string. You only need the Users table and a filter clause.
What is the time complexity of Find Valid Emails?
The time complexity is O(n * L), where n is the number of rows and L is the average email length. Each email is scanned once by the pattern engine. The extra space is O(1) beyond the output.
Is Find Valid Emails asked at Google, Amazon, or Meta?
The problem is tagged Database on FleetCode, but company-specific frequency data is not included in the tags. Practice SQL pattern matching and string filtering, since these topics appear across many database interview rounds.
