Taro Logo

Unique Email Addresses

#21 Most AskedEasy
Topics:
ArraysStrings

Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.

  • For example, in "alice@leetcode.com", "alice" is the local name, and "leetcode.com" is the domain name.

If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.

  • For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address.

If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.

  • For example, "m.y+name@email.com" will be forwarded to "my@email.com".

It is possible to use both of these rules at the same time.

Given an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails.

Example 1:

Input: emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
Output: 2
Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails.

Example 2:

Input: emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"]
Output: 3

Constraints:

  • 1 <= emails.length <= 100
  • 1 <= emails[i].length <= 100
  • emails[i] consist of lowercase English letters, '+', '.' and '@'.
  • Each emails[i] contains exactly one '@' character.
  • All local and domain names are non-empty.
  • Local names do not start with a '+' character.
  • Domain names end with the ".com" suffix.
  • Domain names must contain at least one character before ".com" suffix.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum size of the `emails` array and the maximum length of an individual email string?
  2. Are all input email strings guaranteed to contain a single '@' symbol separating the local name and the domain name?
  3. Can an email address have multiple '+' signs or periods, and how should consecutive special characters like '..', '.+', or '++' be handled?
  4. Are email local names case-insensitive (e.g., 'Test.Email' vs 'testemail'), or is case-insensitivity strictly limited to the domain name?
  5. Can the input array contain empty strings, null values, or invalid email formats that do not conform to standard structure?

Brute Force Solution

Approach

Imagine you have a stack of mail addressed to the exact same people, but written in many messy ways. The brute force approach is like taking every single email address on your list, cleaning them up one by one, and keeping a separate pile for the unique ones.

Here's how the algorithm would work step-by-step:

  1. Take the first email address from your list.
  2. Split the address into the part before the at symbol and the part after the at symbol.
  3. For the first part, erase every character that comes after a plus sign, including the plus sign itself.
  4. Next, remove every single dot found in that first part.
  5. Glue the cleaned first part back together with the untouched second part to get the final official version of that email address.
  6. Compare this final official version against every email address currently sitting in your unique collection pile.
  7. If it is not already in the pile, add it.
  8. Repeat this exact cleaning and comparison process for every single email address given to you.
  9. At the very end, count how many items ended up in your unique collection pile to get your final answer.

Code Implementation

def numUniqueEmails(emails):
    unique_collection_pile = []

    # We process each email individually to simulate cleaning the messy mail pile
    for current_email in emails:
        local_name, domain_name = current_email.split('@')

        if '+' in local_name:
            local_name = local_name.split('+')[0]

        # Dots are ignored in the local name, so we remove them completely
        local_name = local_name.replace('.', '')

        official_email_version = local_name + '@' + domain_name

        # We check uniqueness by comparing against our pile before adding it
        if official_email_version not in unique_collection_pile:
            unique_collection_pile.append(official_email_version)

    return len(unique_collection_pile)

Big(O) Analysis

Time Complexity
O(n * m) – Let n be the number of email addresses in the input list and m be the maximum length of a single email address. For each of the n emails, we iterate through its characters to split, remove plus-sign suffixes, and strip dots, which takes proportional time to the length of the email m. Inserting each cleaned email into a hash set takes average constant time relative to m due to string hashing. This results in approximately n times m total operations, which simplifies to O(n * m).
Space Complexity
O(n) – To determine the number of distinct addresses, the algorithm stores the finalized versions of the emails inside a hash set acting as the unique collection pile. In the worst-case scenario where every single input email address is entirely unique, this hash set will store all N processed strings. Because the length of each individual email string is bound by a small constant factor, the extra memory required scales linearly with the number of emails. Therefore, the auxiliary space complexity is driven by this hash set and evaluates to Big O of N, where N represents the total number of email addresses in the input list.

Optimal Solution

Approach

To find out how many unique email addresses actually receive mail, we need to clean up each address by applying specific formatting rules. By simplifying every email into its true destination form and collecting them in a single place, we can easily count how many distinct destinations exist.

Here's how the algorithm would work step-by-step:

  1. Look at each email address one by one on your list.
  2. Split the email address into two parts by finding the symbol that separates the personal name from the website domain.
  3. Focus only on the first part before that symbol, because this is where the formatting rules apply.
  4. Throw away everything in that first part starting from the very first dot, since dots do not matter for delivery.
  5. Stop reading that first part entirely if you encounter a plus sign, because any text after the plus sign should be completely ignored.
  6. Combine your newly cleaned-up first part with the original website domain part to get the final actual destination.
  7. Add this final destination to a growing collection of unique destinations, making sure the collection automatically ignores any duplicates.
  8. Once you have processed every email address on your list, simply count how many distinct destinations ended up inside your collection.

Code Implementation

def num_unique_emails(email_address_list):
    unique_destination_set = set()

    # Using a set ensures duplicate destinations are automatically discarded.
    for raw_email_address in email_address_list:
        local_name, domain_name = raw_email_address.split('@')

        if '+' in local_name:
            local_name = local_name.split('+')[0]

        # Dots are ignored in local names, so they must be removed.
        local_name = local_name.replace('.', '')

        actual_destination = local_name + '@' + domain_name
        unique_destination_set.add(actual_destination)

    return len(unique_destination_set)

Big(O) Analysis

Time Complexity
O(n) – To process a list of n email addresses, we iterate through each address once and perform string manipulation operations whose cost is bounded by the maximum length of an email, which is a constant. We then insert each cleaned destination into a hash set, where insertions and duplicate checks take place in constant time on average. This results in approximately n operations to process the entire list, which simplifies to O(n).
Space Complexity
O(N) – To determine the number of unique email addresses, we use a hash set to store the final cleaned destinations as we process the list. In the worst-case scenario where every email address in the input is distinct, the hash set will store all N cleaned addresses. Each string stored in the hash set requires additional memory proportional to its length. Therefore, the total auxiliary space complexity scales linearly with the number of email addresses, N, in the input list.

Edge Cases

Empty or null input array of emails
How to Handle:
Return zero immediately since there are no email addresses to process.
Emails with multiple plus signs in the local name
How to Handle:
Ignore all characters starting from the very first plus sign encountered.
Emails containing no local name or an empty domain
How to Handle:
Assume well-formed constraints as per standard problem guarantees or skip invalid formats.
Local names consisting entirely of periods
How to Handle:
Strip all periods resulting in an empty local name that still correctly concatenates with the domain.
Large input arrays with millions of identical emails
How to Handle:
Use a hash set to store processed unique addresses, ensuring efficient O(N) time complexity and deduplication.
Domain names with mixed or uppercase letters
How to Handle:
Preserve the exact casing of the domain name since domains are case-sensitive.
Local names with mixed case letters
How to Handle:
Preserve the casing of the local name because punctuation rules only apply to periods and plus signs, not letters.
0/33 completed