#929

Unique Email Addresses

Easy
ArrayHash TableStringHash MapArray
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 HashSet to store unique email addresses directly, allowing us to efficiently check for duplicates as we process each email.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a HashSet to store unique email addresses.
  2. 2Step 2: For each email, split it into local and domain parts using '@'.
  3. 3Step 3: Remove all dots from the local part and ignore everything after the first plus sign.
  4. 4Step 4: Add the processed email directly to the HashSet.
  5. 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.