Back to blog
Feb 10, 2025
9 min read

Find Users With Valid E-Mails

Find users with valid e-mails where prefix starts with a letter and domain is @leetcode.com

Difficulty: Easy | Acceptance: 36.10% | Paid: No Topics: Database

Table: Users

+---------------+---------+ | Column Name | Type | +---------------+---------+ | user_id | int | | name | varchar | | mail | varchar | +---------------+---------+ user_id is the primary key (column with unique values) for this table. This table contains information of the users signed up in a website. Some e-mails are invalid.

An e-mail is valid if it meets the following criteria:

  1. It must have the format: prefix_name@domain_name
  2. The prefix_name must start with an English letter (a-z or A-Z).
  3. The prefix_name can contain letters, digits, underscores, periods, and dashes.
  4. The domain_name must be ‘@leetcode.com’.

Write a solution to find all users who have valid e-mails.

Return the result table in any order.

Examples

Example 1:

Input: Users table: +---------+-----------+-------------------------+ | user_id | name | mail | +---------+-----------+-------------------------+ | 1 | Winston | winston@leetcode.com | | 2 | Jonathan | jonathanisgreat | | 3 | Annabelle | bella-@leetcode.com | | 4 | Sally | sally.c@leetcode.com | | 5 | Marwan | quarz#2020@leetcode.com | | 6 | David | david69@gmail.com | | 7 | Shapiro | .shapo@leetcode.com | +---------+-----------+-------------------------+ Output: +---------+-----------+-------------------------+ | user_id | name | mail | +---------+-----------+-------------------------+ | 1 | Winston | winston@leetcode.com | | 4 | Sally | sally.c@leetcode.com | +---------+-----------+-------------------------+ Explanation:

  • The mail of user 1 is valid because it starts with ‘w’ and ends with ‘@leetcode.com’.
  • The mail of user 2 is invalid because it does not contain ‘@leetcode.com’.
  • The mail of user 3 is invalid because it starts with a dash.
  • The mail of user 4 is valid because it starts with ‘s’ and ends with ‘@leetcode.com’.
  • The mail of user 5 is invalid because it contains ’#‘.
  • The mail of user 6 is invalid because the domain is not ‘@leetcode.com’.
  • The mail of user 7 is invalid because it starts with a period.

Constraints

1 <= Users.length <= 1000
1 <= user_id <= 1000
name.length <= 100
mail.length <= 100

Approach 1: Using Regular Expression

Intuition Use regex pattern matching to validate emails according to the given rules in a single expression.

Steps

  • Use REGEXP or similar function to match the pattern
  • Pattern: ^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode.com$
  • Select all rows where mail matches this pattern
python
import pandas as pd

def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
    pattern = r'^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\.com$'
    valid_users = users[users['mail'].str.match(pattern)]
    return valid_users[['user_id', 'name', 'mail']]

Complexity

  • Time: O(n × m) where n is number of users and m is average email length
  • Space: O(n) for storing results
  • Notes: Regex provides clean pattern matching but may have overhead

Approach 2: Using String Functions

Intuition Manually check each validation rule using string operations without regex.

Steps

  • Check if email ends with ‘@leetcode.com’
  • Extract prefix before ’@‘
  • Check if prefix starts with a letter
  • Check if all prefix characters are valid (letters, digits, underscore, period, dash)
python
import pandas as pd

def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
    def is_valid(mail):
        if not mail.endswith('@leetcode.com'):
            return False
        prefix = mail.split('@')[0]
        if not prefix or not prefix[0].isalpha():
            return False
        valid_chars = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-')
        return all(c in valid_chars for c in prefix)
    
    valid_users = users[users['mail'].apply(is_valid)]
    return valid_users[['user_id', 'name', 'mail']]

Complexity

  • Time: O(n × m) where n is number of users and m is average email length
  • Space: O(n) for storing results
  • Notes: More verbose but avoids regex overhead, easier to understand

Approach 3: Using LIKE Pattern Matching

Intuition Use SQL-style LIKE pattern matching with early filtering for better performance.

Steps

  • First filter emails ending with ‘@leetcode.com’
  • Then check prefix starts with a letter
  • Finally verify all prefix characters are valid
python
import pandas as pd

def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
    # Filter emails that end with @leetcode.com
    candidates = users[users['mail'].str.endswith('@leetcode.com')]
    
    # Check prefix starts with letter
    candidates = candidates[candidates['mail'].str[0].str.isalpha()]
    
    # Check prefix contains only valid characters
    def has_valid_chars(mail):
        prefix = mail.split('@')[0]
        valid_chars = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-')
        return all(c in valid_chars for c in prefix)
    
    valid_users = candidates[candidates['mail'].apply(has_valid_chars)]
    return valid_users[['user_id', 'name', 'mail']]

Complexity

  • Time: O(n × m) where n is number of users and m is average email length
  • Space: O(n) for storing results
  • Notes: Early filtering can reduce work for invalid emails