#3436
Find Valid Emails
EasyDatabaseRegular ExpressionsString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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- 1Step 1: Use a regular expression to match the valid email format in one go.
- 2Step 2: The regex checks for exactly one '@', valid local part, and valid domain ending with '.com'.
- 3Step 3: Select valid emails directly using the regex match.
- 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.