554/670

554. Unique Email Addresses

Easy

Many mail providers treat several spellings of an address as the same mailbox. For this problem an address has the form local@domain, and two rules apply to the local part only:

  • every . in the local part is ignored — ada.lovelace and adalovelace deliver to the same place;
  • everything from the first + onward in the local part is thrown away — ada+math delivers to ada.

The domain part is always used exactly as written; its dots are meaningful.

You receive an array of strings emails. If one message is sent to every address in the array, return the number of distinct mailboxes that receive at least one message.

Example 1:

Input: emails = ["ada.lovelace+math@hu.dev", "adalovelace@hu.dev", "ada.lovelace@h.u.dev"]

Output: 2

Explanation: The first two both normalize to adalovelace@hu.dev. The third keeps its dots in the domain h.u.dev, which is a different mailbox.

Example 2:

Input: emails = ["a.b+c@mail.com", "ab@mail.com", "a.b.c@mail.com"]

Output: 2

Explanation: a.b+c@mail.com and ab@mail.com both normalize to ab@mail.com; a.b.c@mail.com normalizes to abc@mail.com.

Constraints:

  • 1 ≤ emails.length ≤ 100
  • 1 ≤ emails[i].length ≤ 100
  • Each address contains exactly one '@' with a non-empty local part and a non-empty domain.
  • Addresses consist of lowercase English letters, '.', '+', and '@'.
  • The local part does not start with '+', and the piece before the first '+' is non-empty.
  • The domain contains at least one '.' and no '+'.

Hints:

Don't compare addresses to each other. Instead, rewrite each address into a single canonical spelling — what would that rewrite look like?

Split at the '@' once. In the local half: cut at the first '+', then delete dots. Reattach the untouched domain and drop every canonical string into a hash set; the answer is the set's size.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: emails = ["ada.lovelace+math@hu.dev", "adalovelace@hu.dev", "ada.lovelace@h.u.dev"]

Expected output: 2