Every email consists of a local name and a domain name, separated by the @ sign.

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

Besides lowercase letters, these emails may contain '.'s or '+'s.

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.  For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address.  (Note that this rule does not apply for domain names.)

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, for example m.y+name@email.com will be forwarded to my@email.com.  (Again, this rule does not apply for domain names.)

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

Given a list of emails, we send one email to each address in the list.  How many different addresses actually receive mails? 

Problem Clarification

What is the boundary of local name and domain name? The last ‘@’ symbol. The rules apply to local name only.

Idea – 1

We break each email into local name and domain name. We then apply the rules on the local name portion, the result is a normalized local name. We then combine the normalized local name with the domain name to find a desired email and we keep track of unique such emails using a hash set. If there are n strings and the length of the longest string is m, the time and space both is O(m\cdot n).

class Solution {
    public int numUniqueEmails(String[] emails) {
        HashSet<String> emailSet = new HashSet<String>();
        for(String email : emails)
        {
            int indexOfLastAddressSymbol = email.lastIndexOf('@');
            String localName = email.substring(0, indexOfLastAddressSymbol);
            String domainName = email.substring(indexOfLastAddressSymbol);
            
            String normalizedEmail = normalize(localName)+domainName;
            emailSet.add(normalizedEmail);
        }
        
        return emailSet.size();
    }
    
    private String normalize(String localName)
    {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < localName.length(); ++i)
        {
            char c = localName.charAt(i);
            if(c == '+')
            {
                break;
            }
            else if(c != '.')
            {
                sb.append(c);
            }
        }
        
        return sb.toString();
    }
}


Runtime: 6 ms, faster than 99.60% of Java online submissions for Unique Email Addresses.
Memory Usage: 38.6 MB, less than 95.07% of Java online submissions for Unique Email Addresses.

Leave a comment