Talentd
FleetCode
Make and follow sheets.Sign in

Find Users With Valid E-Mails solution and explanation

EasyDatabase6 min read35.2% acceptanceUpdated 9 Apr 2026
Find Users With Valid E-Mails | Leetcode 1517 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 10:16 · 9K viewsWatch on YouTube
9 more videos on this problem
  1. Find Users With Valid E-Mails | Leetcode 1517 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 10:16 · 9K views
  2. 50. Find Users With Valid E-Mails | SQL Interview Questions and AnswersStart Practicing · 6:55 · 7K views
  3. LeetCode 1517 "Find Users With Valid E-Mails" Apple Interview SQL Question with Detailed ExplanationEveryday Data Science · 8:12 · 6K views
  4. LeetCode 1517: Find Users With Valid E-Mails [SQL]Frederik Müller · 10:54 · 2K views
  5. LeetCode - 1517. Find Users With Valid E-Mails (SQL)Chain Of Thought · 4:56 · 556 views
  6. 30 Days of Pandas Day 8 | Find Users With Valid E-Mails | LeetCode 1517DevTechMinds · 4:20 · 465 views
  7. 1517. Find Users With Valid E-Mails | SQL | #50questions #leetcodechallenge #databaseSheCodes · 5:01 · 270 views
  8. #LeetCode 1517 | Find Users With Valid E-Mails #SQLSleepy Cracker · 3:49 · 219 views
  9. Find Users With Valid Emails || Leetcode SQL QuestionsCodeInQueries · 8:11 · 125 views
  10. leetcode Pandas 1517. Find Users With Valid E-MailsTech classes · 8:43 · 124 views

The problem

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.

Write a solution to find the users who have valid emails.

A valid e-mail has a prefix name and a domain where:

  • The prefix name is a string that may contain letters (upper or lower case), digits, underscore '_', period '.', and/or dash '-'. The prefix name must start with a letter.
  • The domain is '@leetcode.com'.

Return the result table in any order.

The result format is in the following example.

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.come@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    |
| 3       | Annabelle | bella-@leetcode.com     |
| 4       | Sally     | sally.come@leetcode.com |
+---------+-----------+-------------------------+
Explanation: 
The mail of user 2 does not have a domain.
The mail of user 5 has the # sign which is not allowed.
The mail of user 6 does not have the leetcode domain.
The mail of user 7 starts with a period.

Approach overview

Problem Overview: Given a Users table with user_id, name, and mail, return users whose email addresses are valid. A valid email must start with a letter, contain only letters, digits, underscores, periods, or hyphens before the @, and must end exactly with @leetcode.com.

Approach 1: Regular Expression Filtering (O(n * m) time, O(1) space)

This approach uses SQL regular expression matching to validate the email format directly in the query. You apply a REGEXP pattern such as '^[A-Za-z][A-Za-z0-9_.-]*@leetcode\\.com$' to the mail column. The pattern enforces three rules: the first character must be a letter, the local part can contain letters, digits, underscores, periods, or hyphens, and the domain must match @leetcode.com exactly. The database scans each row and checks the regex against the email string. Time complexity is O(n * m), where n is the number of rows and m is the email length, since regex engines inspect characters in the string. Space complexity is O(1) because filtering happens during the query without additional storage. This method is concise and maps directly to the problem constraints, which makes it the most common solution in database interview questions involving regular expressions.

Approach 2: Parsing and Checking (O(n * m) time, O(1) space)

Instead of relying on regex, you can manually validate each email using string operations. Split the email around @ and confirm the domain equals leetcode.com. Then validate the local part: check that the first character is a letter and iterate through the remaining characters ensuring each belongs to the allowed set (letters, digits, underscore, period, or hyphen). This logic can be implemented in application code or through SQL string functions such as SUBSTRING, LIKE, or character checks. Time complexity remains O(n * m) because every character may be inspected, while space complexity stays O(1). This approach is useful when regex support is limited or when you want explicit control over validation logic using string processing.

Recommended for interviews: Regular expression filtering is the expected solution for this problem. It expresses the constraints in a single pattern and keeps the SQL query short and readable. Manual parsing shows deeper understanding of validation rules and works in environments without regex support, but interviewers typically expect the regex-based query because it directly models the problem statement.

Approach 1: Approach 1: Regular Expression Filtering

In this approach, we use regular expressions to check for valid emails. The regular expression will ensure that the email format adheres to the specified rules: the prefix starts with a letter and consists only of permitted characters, followed by '@leetcode.com'. This method efficiently checks the constraints by leveraging regular expressions, which are well-suited for pattern matching tasks.

import re
def find_valid_emails(users):
    pattern = r'^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\.com$'
    valid_emails = [user for user in users if re.match(pattern, user['mail'])]
    return valid_emails

# Example usage
users = [
    {'user_id': 1, 'name': 'Winston', 'mail': 'winston@leetcode.com'},
    {'user_id': 2, 'name': 'Jonathan', 'mail': 'jonathanisgreat'},
    {'user_id': 3, 'name': 'Annabelle', 'mail': 'bella-@leetcode.com'},
    {'user_id': 4, 'name': 'Sally', 'mail': 'sally.come@leetcode.com'},
    {'user_id': 5, 'name': 'Marwan', 'mail': 'quarz#2020@leetcode.com'},
    {'user_id': 6, 'name': 'David', 'mail': 'david69@gmail.com'},
    {'user_id': 7, 'name': 'Shapiro', 'mail': '.shapo@leetcode.com'}
]

valid_users = find_valid_emails(users)
print(valid_users)
import java.util.*;
import java.util.regex.*;

public class ValidEmails {
    public static List<Map<String, String>> findValidEmails(List<Map<String, String>> users) {
        List<Map<String, String>> validEmails = new ArrayList<>();
        String pattern = "^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\\.com$";
        Pattern regex = Pattern.compile(pattern);

        for (Map<String, String> user : users) {
            String email = user.get("mail");
            Matcher matcher = regex.matcher(email);
            if (matcher.matches()) {
                validEmails.add(user);
            }
        }

        return validEmails;
    }

    public static void main(String[] args) {
        List<Map<String, String>> users = new ArrayList<>();
        users.add(new HashMap<>(Map.of("user_id", "1", "name", "Winston", "mail", "winston@leetcode.com")));
        users.add(new HashMap<>(Map.of("user_id", "2", "name", "Jonathan", "mail", "jonathanisgreat")));
        users.add(new HashMap<>(Map.of("user_id", "3", "name", "Annabelle", "mail", "bella-@leetcode.com")));
        users.add(new HashMap<>(Map.of("user_id", "4", "name", "Sally", "mail", "sally.come@leetcode.com")));
        users.add(new HashMap<>(Map.of("user_id", "5", "name", "Marwan", "mail", "quarz#2020@leetcode.com")));
        users.add(new HashMap<>(Map.of("user_id", "6", "name", "David", "mail", "david69@gmail.com")));
        users.add(new HashMap<>(Map.of("user_id", "7", "name", "Shapiro", "mail", ".shapo@leetcode.com")));

        List<Map<String, String>> validUsers = findValidEmails(users);
        System.out.println(validUsers);
    }
}
function findValidEmails(users) {
    let validEmails = [];
    let pattern = /^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\.com$/;
    
    for (let user of users) {
        if (pattern.test(user.mail)) {
            validEmails.push(user);
        }
    }
    return validEmails;
}

// Example usage
const users = [
    {"user_id": 1, "name": "Winston", "mail": "winston@leetcode.com"},
    {"user_id": 2, "name": "Jonathan", "mail": "jonathanisgreat"},
    {"user_id": 3, "name": "Annabelle", "mail": "bella-@leetcode.com"},
    {"user_id": 4, "name": "Sally", "mail": "sally.come@leetcode.com"},
    {"user_id": 5, "name": "Marwan", "mail": "quarz#2020@leetcode.com"},
    {"user_id": 6, "name": "David", "mail": "david69@gmail.com"},
    {"user_id": 7, "name": "Shapiro", "mail": ".shapo@leetcode.com"}
];

console.log(findValidEmails(users));
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class ValidEmails {
    public static List<Dictionary<string, string>> FindValidEmails(List<Dictionary<string, string>> users) {
        List<Dictionary<string, string>> validEmails = new List<Dictionary<string, string>>();
        string pattern = "^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\\.com$";
        Regex regex = new Regex(pattern);

        foreach (var user in users) {
            if (regex.IsMatch(user["mail"])) {
                validEmails.Add(user);
            }
        }
        return validEmails;
    }

    public static void Main() {
        List<Dictionary<string, string>> users = new List<Dictionary<string, string>>() {
            new Dictionary<string, string>() { {"user_id", "1"}, {"name", "Winston"}, {"mail", "winston@leetcode.com"} },
            new Dictionary<string, string>() { {"user_id", "2"}, {"name", "Jonathan"}, {"mail", "jonathanisgreat"} },
            new Dictionary<string, string>() { {"user_id", "3"}, {"name", "Annabelle"}, {"mail", "bella-@leetcode.com"} },
            new Dictionary<string, string>() { {"user_id", "4"}, {"name", "Sally"}, {"mail", "sally.come@leetcode.com"} },
            new Dictionary<string, string>() { {"user_id", "5"}, {"name", "Marwan"}, {"mail", "quarz#2020@leetcode.com"} },
            new Dictionary<string, string>() { {"user_id", "6"}, {"name", "David"}, {"mail", "david69@gmail.com"} },
            new Dictionary<string, string>() { {"user_id", "7"}, {"name", "Shapiro"}, {"mail", ".shapo@leetcode.com"} }
        };

        var validEmails = FindValidEmails(users);
        foreach(var user in validEmails) {
            Console.WriteLine(string.Join(", ", user));
        }
    }
}

This Python solution utilizes the 're' module to define a regular expression pattern that matches valid emails. The pattern checks if the email starts with a letter and is followed by any combination of allowed characters before the fixed domain '@leetcode.com'. The function iterates through the list of users, filters valid emails using 're.match', and returns the filtered list.

Complexity

The time complexity of this solution is O(n), where n is the number of users, as each email is scanned once. The space complexity is O(n) as we store all valid users in a list.

Try this approach in the editor

Approach 2: Approach 2: Parsing and Checking

This approach involves manually parsing the email to check the prefix and domain components. We split the email at the '@' character and validate both parts separately. This is an alternative to regex that provides a more step-by-step checking method.

def find_valid_emails(users):
    def is_valid_email(mail):
        if '@leetcode.com' not in mail:
            return False
        prefix, domain = mail.split('@', 1)
        if domain != 'leetcode.com':
            return False
        if not prefix or not prefix[0].isalpha():
            return False
        for char in prefix:
            if not (char.isalnum() or char in '._-'):
                return False
        return True

    valid_emails = [user for user in users if is_valid_email(user['mail'])]
    return valid_emails

# Example usage
users = [
    {'user_id': 1, 'name': 'Winston', 'mail': 'winston@leetcode.com'},
    {'user_id': 2, 'name': 'Jonathan', 'mail': 'jonathanisgreat'},
    {'user_id': 3, 'name': 'Annabelle', 'mail': 'bella-@leetcode.com'},
    {'user_id': 4, 'name': 'Sally', 'mail': 'sally.come@leetcode.com'},
    {'user_id': 5, 'name': 'Marwan', 'mail': 'quarz#2020@leetcode.com'},
    {'user_id': 6, 'name': 'David', 'mail': 'david69@gmail.com'},
    {'user_id': 7, 'name': 'Shapiro', 'mail': '.shapo@leetcode.com'}
]

valid_users = find_valid_emails(users)
print(valid_users)
import java.util.*;

public class ValidEmailsCheck {
    public static List<Map<String, String>> findValidEmails(List<Map<String, String>> users) {
        List<Map<String, String>> validEmails = new ArrayList<>();

        for (Map<String, String> user : users) {
            String email = user.get("mail");
            if (isValidEmail(email)) {
                validEmails.add(user);
            }
        }
        return validEmails;
    }

    private static boolean isValidEmail(String email) {
        if (!email.contains("@leetcode.com")) {
            return false;
        }
        String[] parts = email.split("@", 2);
        if (parts.length != 2 || !parts[1].equals("leetcode.com")) {
            return false;
        }

        String prefix = parts[0];
        if (prefix.isEmpty() || !Character.isLetter(prefix.charAt(0))) {
            return false;
        }
        for (char c : prefix.toCharArray()) {
            if (!Character.isLetterOrDigit(c) && c != '.' && c != '_' && c != '-') {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        List<Map<String, String>> users = new ArrayList<>();
        users.add(new HashMap<>(Map.of("user_id", "1", "name", "Winston", "mail", "winston@leetcode.com")));
        users.add(new HashMap<>(Map.of("user_id", "2", "name", "Jonathan", "mail", "jonathanisgreat")));
        users.add(new HashMap<>(Map.of("user_id", "3", "name", "Annabelle", "mail", "bella-@leetcode.com")));
        users.add(new HashMap<>(Map.of("user_id", "4", "name", "Sally", "mail", "sally.come@leetcode.com")));
        users.add(new HashMap<>(Map.of("user_id", "5", "name", "Marwan", "mail", "quarz#2020@leetcode.com")));
        users.add(new HashMap<>(Map.of("user_id", "6", "name", "David", "mail", "david69@gmail.com")));
        users.add(new HashMap<>(Map.of("user_id", "7", "name", "Shapiro", "mail", ".shapo@leetcode.com")));

        List<Map<String, String>> validUsers = findValidEmails(users);
        System.out.println(validUsers);
    }
}

This Python function manually splits the email at '@', checks if the domain is 'leetcode.com', and ensures that the prefix starts with a letter and contains only allowed characters. This approach is more granular and does not use regex, making it useful for understanding email validation through conditional checks.

Complexity

The time complexity is O(n * m), where n is the number of users and m is the length of the largest email string due to manual character checking. The space complexity is O(n) for the result list.

Try this approach in the editor

Approach 3: REGEXP Pattern Matching

We can use a regular expression to match valid email formats. The expression ensures that the username part meets the required rules and that the domain is fixed as @leetcode.com.

# Write your MySQL query statement below
SELECT *
FROM Users
WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\\.com$' AND BINARY mail LIKE '%@leetcode.com';
import pandas as pd


def valid_emails(users: pd.DataFrame) -> pd.DataFrame:
    pattern = r"^[A-Za-z][A-Za-z0-9_.-]*@leetcode\.com$"
    mask = users["mail"].str.match(pattern, flags=0, na=False)
    return users.loc[mask, ["user_id", "name", "mail"]]
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Regular Expression Filtering

The time complexity of this solution is O(n), where n is the number of users, as each email is scanned once. The space complexity is O(n) as we store all valid users in a list.

Approach 2: Parsing and Checking

The time complexity is O(n * m), where n is the number of users and m is the length of the largest email string due to manual character checking. The space complexity is O(n) for the result list.

REGEXP Pattern Matching–

Complexity analysis

ApproachTimeSpaceWhen to Use
Regular Expression FilteringO(n * m)O(1)Best for SQL queries where regex support exists and validation rules map cleanly to a pattern
Parsing and CheckingO(n * m)O(1)Useful when regex is unavailable or when validation must be implemented using explicit string logic

Frequently asked questions

Is Find Users With Valid E-Mails easy or hard?

Find Users With Valid E-Mails is classified as an Easy problem on LeetCode. The challenge is understanding the exact email format rules and translating them into a correct regex or string validation check.

Find Users With Valid E-Mails Python/Java solution

In SQL-based environments you typically solve it with a REGEXP filter. In Python or Java implementations, iterate through the list of users and validate emails using a regex pattern or manual character checks before returning the valid records.

How to solve Find Users With Valid E-Mails in O(n)?

Process each row once and validate the email format during the scan. In SQL, apply a REGEXP condition like ^[A-Za-z][A-Za-z0-9_.-]*@leetcode\\.com$ to the mail column. The query filters valid emails in a single pass through the table.

What is the best approach for Find Users With Valid E-Mails?

The regular expression filtering approach is the most practical solution. A SQL REGEXP condition checks that the email starts with a letter, allows valid characters in the local part, and ends with @leetcode.com. This method scans each row once and keeps the query short and readable.

Is Find Users With Valid E-Mails asked at Google/Amazon/Meta?

Database filtering and string validation questions like this appear in SQL interview rounds at many companies, including large tech firms. They test familiarity with regex, string constraints, and SQL filtering rather than complex algorithms.

What data structure is used in Find Users With Valid E-Mails?

The problem operates directly on a database table and primarily uses string pattern matching. No additional data structures are required because each email is validated independently during the query.

What is the time complexity of Find Users With Valid E-Mails?

Both common approaches run in O(n * m) time, where n is the number of rows in the Users table and m is the average email length. Each email string must be checked against a regex pattern or validated character by character.

Comments

Now write it yourselfClose this page and solve Find Users With Valid E-Mails in the editor, without looking.
Practise Find Users With Valid E-Mails