We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Unique Email Addresses

Number: 965

Difficulty: Easy

Paid? No

Companies: Google, Intuit, Apple, Wix


Problem Description

Given an array of email addresses, apply specific transformation rules to the local part of each email. The rules are: ignore any periods ('.') and ignore any characters after a plus ('+') in the local name. The domain name remains unchanged. The goal is to count the number of unique email addresses after transformation.


Key Insights

  • Split each email into local and domain parts using the '@' character.
  • In the local part, ignore everything after the first '+'.
  • Remove all periods ('.') from the processed local part.
  • Reconstruct the normalized email and use a set to track unique emails.
  • Return the count of unique emails.

Space and Time Complexity

Time Complexity: O(n * m) where n is the number of emails and m is the average length of an email, as each email is processed character by character. Space Complexity: O(n * m) in the worst case where all processed emails are unique and stored in a set.


Solution

The solution involves iterating through each email and normalizing it by:

  1. Splitting the email string using the '@' delimiter.
  2. Processing the local part:
    • If a '+' exists in the local part, slice the string up to the plus sign.
    • Remove all '.' characters from the sliced local part.
  3. Combining the processed local part with the domain to form the normalized email.
  4. Adding the normalized email to a set to handle duplicates.
  5. Returning the size of the set which represents the number of unique email addresses.

Code Solutions

def numUniqueEmails(emails):
    unique_emails = set()  # Set to store unique normalized emails.
    for email in emails:
        local, domain = email.split('@')  # Split email into local and domain.
        # Process the local part to ignore characters after '+'.
        if '+' in local:
            local = local[:local.index('+')]
        # Remove all periods from the local part.
        local = local.replace('.', '')
        # Reconstruct the normalized email.
        normalized_email = local + '@' + domain
        unique_emails.add(normalized_email)
    return len(unique_emails)

# Example usage:
emails = ["test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com", "testemail+david@lee.tcode.com"]
print(numUniqueEmails(emails))  # Output: 2
← Back to All Questions