#3436

Find Valid Emails

Easy
DatabaseRegular ExpressionsString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a single pass through the emails while applying regular expressions to validate the format. This reduces the number of checks and improves efficiency.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a regular expression to match the valid email format in one go.
  2. 2Step 2: The regex checks for exactly one '@', valid local part, and valid domain ending with '.com'.
  3. 3Step 3: Select valid emails directly using the regex match.
  4. 4Step 4: Order the results by user_id.
solution.py1 lines
1SELECT user_id, email FROM Users WHERE email REGEXP '^[A-Za-z0-9_]+@[A-Za-z]+\.com$' ORDER BY user_id;

Complexity note: The time complexity is O(n) because we are scanning through the list of emails once and applying a regex match which is efficient for this case.

  • 1Using regex can simplify validation checks.
  • 2Validating emails requires careful attention to format.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.