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.
- Clean, then compare pairsO(n²·L)
- 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
| Approach | Time | Relative work for 100 emails | Verdict |
|---|---|---|---|
| Clean, then compare pairs | O(n²·L) | Works; repeats comparisons | |
| Clean into a hash set | O(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.comanda@bc.comare different inboxes: the rules skip the domain. - A `+` in the domain.
a@b+c.comkeeps its+; only the local part is cut. - Several `+` signs.
ab+c+d@e.comis cut at the first one, givingab@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
- 1Clarify. Do the rules apply to the domain? Can there be more than one
+? - 2Name the idea. Map each address to the inbox it reaches; the answer is how many distinct inboxes there are.
- 3Give the slow count. Comparing each cleaned address with all earlier ones works but is O(n²·L).
- 4Use a set. Insert each cleaned address into a hash set and return its size: one pass.
- 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?