#929
Unique Email Addresses
EasyArrayHash TableStringHash MapArray
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 HashSet to store unique email addresses directly, allowing us to efficiently check for duplicates as we process each email.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a HashSet to store unique email addresses.
- 2Step 2: For each email, split it into local and domain parts using '@'.
- 3Step 3: Remove all dots from the local part and ignore everything after the first plus sign.
- 4Step 4: Add the processed email directly to the HashSet.
- 5Step 5: Return the size of the HashSet as the count of unique email addresses.
solution.py9 lines
1def numUniqueEmails(emails):
2 unique_emails = set()
3 for email in emails:
4 local, domain = email.split('@')
5 local = local.replace('.', '')
6 if '+' in local:
7 local = local.split('+')[0]
8 unique_emails.add(local + '@' + domain)
9 return len(unique_emails)ℹ
Complexity note: The complexity is O(n) because we process each email once and use a HashSet to store unique emails, which allows for average O(1) time complexity for insertions.
- 1The local part of an email can be modified by removing dots and ignoring characters after a plus sign.
- 2Using a HashSet allows for efficient storage and retrieval of unique email addresses.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.