Skip to content
Problem 929 · LeetCode 929(opens in a new tab)

Unique Email Addresses

EasyHash tables

Each address in emails has a local part, then an @, then a domain. The mail server applies two rules to the local part only. Any . in it is ignored, so j.o@x.com and jo@x.com reach the same inbox. A + and everything after it in the local part is ignored too, so jo+news@x.com also reaches jo@x.com.

The domain is never changed by these rules. One message goes to every entry in emails. Return how many different inboxes actually get mail.

Example 1

Input:  emails = ["ab.c+x@mail.com", "abc+yy@mail.com", "a.bc@ma.il.com"]
Output: 2
Why:    the first two reach abc@mail.com; the third is abc@ma.il.com
2 more examples and the constraints

Example 2

Input:  emails = ["x@a.com", "y@a.com", "x@b.com"]
Output: 3
Why:    no rule applies, and all three differ

Example 3

Input:  emails = ["p+q.r@s.com", "p@s.com"]
Output: 1
Why:    the dot after the + is cut off with it, so both are p@s.com

Constraints

  • 1 ≤ length of emails ≤ 100
  • 1 ≤ length of each email ≤ 100
  • Only lowercase letters, ., + and exactly one @
  • The local part does not start with +; the domain ends in .com

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Clean, then compare pairsO(n²·L)
  2. Clean into a hash setO(n·L)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100 emailsVerdict
Clean, then compare pairsO(n²·L)
Works; repeats comparisons
Clean into a hash setO(n·L)
Best; one pass

n = number of emails, L = length of an email.

Edge cases to test

  • Dots in the domain. a@b.c.com and a@bc.com are different inboxes: the rules skip the domain.
  • A `+` in the domain. a@b+c.com keeps its +; only the local part is cut.
  • Several `+` signs. ab+c+d@e.com is cut at the first one, giving ab@e.com.
  • One email. A single address is one inbox.

Common mistakes

  • Removing dots from the whole address, domain included.
  • Cutting at the last + instead of the first one.
  • Counting the original strings instead of the cleaned ones.

How to talk through it

  1. 1Clarify. Do the rules apply to the domain? Can there be more than one +?
  2. 2Name the idea. Map each address to the inbox it reaches; the answer is how many distinct inboxes there are.
  3. 3Give the slow count. Comparing each cleaned address with all earlier ones works but is O(n²·L).
  4. 4Use a set. Insert each cleaned address into a hash set and return its size: one pass.
  5. 5Test out loud. Try dots in the domain, a dot after the +, and two + signs.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?