KatInterview

965. Unique Email Addresses

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to count the number of unique email addresses from a given list. The uniqueness is determined after applying a set of normalization rules to each email address. An email address consists of a local name and a domain name, separated by an '@'. The rules are:

Solution

Unique Email Addresses in Python

class Solution:
    def numUniqueEmails(self, emails: List[str]) -> int:
        # Use a set to store unique canonical email addresses.
        unique_emails = set()

        for email in emails:
            # Split the email into local and domain parts.
            local, domain = email.split('@')

            # Process the local part:
            # 1. Handle the '+' rule: take the part before the first '+'.
            local = local.split('+', 1)[0]
            
            # 2. Handle the '.' rule: remove all dots.
            local = local.replace('.', '')

            # Reconstruct the canonical email and add it to the set.
            canonical_email = local + '@' + domain
            unique_emails.add(canonical_email)

        # The length of the set is the number of unique emails.
        return len(unique_emails)

Unique Email Addresses in Java

class Solution {
    public int numUniqueEmails(String[] emails) {
        // Use a HashSet to store unique canonical email addresses.
        Set<String> uniqueEmails = new HashSet<>();

        for (String email : emails) {
            // Find the position of '@' to separate local and domain names.
            int atIndex = email.indexOf('@');
            String localName = email.substring(0, atIndex);
            String domainName = email.substring(atIndex);

            // Process the local name using a StringBuilder for efficiency.
            StringBuilder processedLocal = new StringBuilder();
            for (char c : localName.toCharArray()) {
                // If a '+' is found, ignore the rest of the local part.
                if (c == '+') {
                    break;
                }
                // If a '.' is found, just skip it.
                if (c == '.') {
                    continue;
                }
                // Otherwise, append the character.
                processedLocal.append(c);
            }
            
            // Combine the processed local name with the domain name and add to the set.
            uniqueEmails.add(processedLocal.toString() + domainName);
        }

        // The size of the set is the number of unique emails.
        return uniqueEmails.size();
    }
}

Unique Email Addresses in C++

class Solution {
public:
    int numUniqueEmails(vector<string>& emails) {
        // Use an unordered_set to store unique canonical email addresses.
        unordered_set<string> unique_emails;

        for (const string& email : emails) {
            string processed_local;
            // Find the position of '@' to separate local and domain names.
            size_t at_pos = email.find('@');
            string local_part = email.substr(0, at_pos);
            string domain_part = email.substr(at_pos);

            // Process the local part according to the rules.
            for (char c : local_part) {
                // If a '+' is found, ignore the rest of the local part.
                if (c == '+') {
                    break;
                }
                // If a '.' is found, just skip it.
                if (c == '.') {
                    continue;
                }
                // Otherwise, append the character to the processed local name.
                processed_local += c;
            }

            // Combine the processed local name with the domain name and add to the set.
            unique_emails.insert(processed_local + domain_part);
        }

        // The size of the set is the number of unique emails.
        return unique_emails.size();
    }
};

Unique Email Addresses in TypeScript

function numUniqueEmails(emails: string[]): number {
    // Use a Set to store unique canonical email addresses.
    const uniqueEmails = new Set<string>();

    for (const email of emails) {
        // Split the email into local and domain parts.
        let [local, domain] = email.split('@');

        // Process the local part:
        // 1. Handle the '+' rule: find the index of the first '+' and take the substring before it.
        const plusIndex = local.indexOf('+');
        if (plusIndex !== -1) {
            local = local.substring(0, plusIndex);
        }

        // 2. Handle the '.' rule: remove all dots. The 'g' flag ensures all occurrences are replaced.
        local = local.replace(/\./g, '');

        // Reconstruct the canonical email and add it to the set.
        const canonicalEmail = local + '@' + domain;
        uniqueEmails.add(canonicalEmail);
    }

    // The size of the set is the number of unique emails.
    return uniqueEmails.size;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.