Unique Email Addresses

Count how many different inboxes a list of email addresses reaches, when a local name can be written in several ways.

An email address has two parts joined by '@': the local name before it and the domain name, or just the domain, after it. In "alice.z+news@cscode.io", the local name is "alice.z+news" and the domain name is "cscode.io". Two rules apply to the local name only:

The domain name is used exactly as written. You are given an array of strings emails, each a valid address with exactly one '@'. Return how many different addresses actually receive mail.

Example 1
Input: emails = ["user.jc@cscode.io", "u.s.e.r.jc+test@cscode.io", "user.jc+test@cs.code.io"]
Output: 2
Explanation: the first two reach "userjc@cscode.io". The third reaches "userjc@cs.code.io": the dots in the domain name stay, so it is a different address.
Example 2
Input: emails = ["ab@cscode.io", "a.b+x.y@cscode.io", "ab+@cscode.io"]
Output: 1
Explanation: all three reach "ab@cscode.io".
Solution

The Idea

Some mail services let you write one address in several ways. Mail sent to alice.z@cscode.io and to alicez@cscode.io lands in the same inbox. So does mail to alice+news@cscode.io, and people use such a '+' part to see which site a message came from. A list of addresses can therefore point to fewer inboxes than it has entries.

Look at Example 1. The three strings are all different, yet the answer is 2. Comparing the strings as they are tells us nothing, since no two of them are equal. So how do we see which ones lead to the same inbox?

Rewrite each address into the one form that mail actually reaches. Look at the picture below.

Two addresses cleaned character by character. In u.s.e.r.jc+test@cscode.io the dots of the local name are skipped and the '+' and everything after it are ignored, so it becomes userjc@cscode.io. user.jc+test@cs.code.io becomes userjc@cs.code.io, because the dots in the domain stay.

The first row is the second address of Example 1, u.s.e.r.jc+test@cscode.io, split at '@' into its local name and its domain. The four dots in the local name are skipped, and the '+' is ignored together with "test" after it. What remains of the local name is userjc, the domain cscode.io is kept, and the address becomes userjc@cscode.io. The first address, user.jc@cscode.io, gives the same string once its one dot is skipped.

The second row is the third address, user.jc+test@cs.code.io. Its local name is cleaned the same way, to userjc. Its domain is cs.code.io, and those dots stay, so it becomes userjc@cs.code.io, a different string.

So two addresses reach the same inbox exactly when their rewritten forms are equal strings. A fixed form like this, which every way of writing the same thing turns into, is called a normal form. Counting inboxes becomes counting different normal forms.

Solution Approach

Turning that idea into code means settling three things: how to find the local name, how to clean it, and how to count the different normal forms.

Finding the local name

Where does the local name end? At the '@'. email.indexOf('@') gives its position, and the characters before it are the local name. email.substring(at), where at is that position, returns the '@' and the domain, which stay as they are.

Why not remove every dot at once with email.replace(".", "")? It is shorter, but the domain loses its dots too. On Example 1, all three addresses then become userjc@cscodeio, and the count comes out as 1 instead of 2.

Cleaning the local name

What should happen to each character of the local name? Walk through it from left to right and collect the characters to keep in a StringBuilder, a Java class that builds a string piece by piece. A dot is skipped. A '+' ends the walk at once, since nothing after it counts, not even dots. Any other character is appended.

Counting different normal forms

How do we count the different normal forms? The simple way compares each one with all the others, about n²/2 comparisons for n addresses. A HashSet does it in one pass. It is a Java collection that keeps one copy of each value, so adding a string it already holds changes nothing. Once every normal form is added, the size of the set is the answer.

Java Solution

The method numUniqueEmails works in these steps, with the help of normalise:

  1. First, create an empty HashSet called addresses, then loop over emails and pass each address to normalise.
  2. In normalise, find the '@' with email.indexOf('@') and keep its position in at.
  3. A loop then walks the local name, positions 0 to at - 1, and builds the cleaned name in a StringBuilder called local. A '+' stops the loop with break, a dot is skipped, and any other character is appended.
  4. normalise returns local followed by email.substring(at), the '@' and the domain unchanged.
  5. Back in the loop over emails, add that normal form to addresses. When the loop is done, return addresses.size().

The main method prints the normal form of each address in Example 1 and their count. Then it tries one address from Example 2, the count for Example 2, and two addresses whose local names start with '+'.

Java
import java.util.HashSet;
import java.util.Set;

public class UniqueEmailAddresses {

    static String normalise(String email) {
        int at = email.indexOf('@');
        StringBuilder local = new StringBuilder();
        for (int i = 0; i < at; i++) {
            char c = email.charAt(i);
            if (c == '+') {
                break;                        // ignore the rest of the local name
            }
            if (c != '.') {
                local.append(c);              // a dot is skipped, anything else is kept
            }
        }
        return local + email.substring(at);   // the '@' and the domain stay as written
    }

    public static int numUniqueEmails(String[] emails) {
        Set<String> addresses = new HashSet<>();
        for (String email : emails) {
            addresses.add(normalise(email));
        }
        return addresses.size();
    }

    public static void main(String[] args) {
        String[] example = {"user.jc@cscode.io", "u.s.e.r.jc+test@cscode.io",
                "user.jc+test@cs.code.io"};
        for (String email : example) {
            System.out.println(email + " -> " + normalise(email));
        }
        System.out.println(numUniqueEmails(example));
        System.out.println(normalise("a.b+x.y@cscode.io"));
        System.out.println(numUniqueEmails(new String[] {"ab@cscode.io", "a.b+x.y@cscode.io",
                "ab+@cscode.io"}));
        System.out.println(numUniqueEmails(new String[] {"+news@cscode.io", "+mail@cscode.io"}));
    }
}

Running it prints:

Output
user.jc@cscode.io -> userjc@cscode.io
u.s.e.r.jc+test@cscode.io -> userjc@cscode.io
user.jc+test@cs.code.io -> userjc@cs.code.io
2
ab@cscode.io
1
1

Look at the first three lines. user.jc@cscode.io and u.s.e.r.jc+test@cscode.io both end as userjc@cscode.io, while the third address keeps the dot in cs.code.io. That leaves two different normal forms, and the fourth line prints 2.

The fifth line shows a.b+x.y@cscode.io cleaned to ab@cscode.io. The dot in x.y never matters, because the loop stops at the '+' before it gets there. So all three addresses of Example 2 share one normal form, and the next line prints 1.

The last line comes from +news@cscode.io and +mail@cscode.io. Their local names stop at the very first character, so both become @cscode.io and the count is 1.

The original implementation, UniqueEmailAddresses.java, is on GitHub.

Complexity

The work is one pass over the characters of each address, plus adding its normal form to the set.

  • Time: O(L), where L is the total number of characters in all the addresses. For each address, indexOf, the loop and substring each read its characters at most once, and hashing the normal form reads it once more.
  • Space: O(L) for the set. In the worst case every address is different, and the HashSet stores one normal form for each, nearly as long as the original.

Turning each item into a normal form and comparing those forms is also how Group Anagrams works.