Unique Email Addresses (LeetCode 929): Solution and Explanation
Rewrite each email to the inbox that actually receives it, ignoring dots and anything after a plus in the local name, then count how many distinct inboxes remain.
Intuition
Two different strings can deliver to the same inbox, so comparing raw strings overcounts. What matters is the address after the forwarding rules are applied.
Every email has exactly one canonical form: the local name with everything from the first '+' removed and all dots stripped, followed by the untouched domain. Once each email is in that form, equal inboxes become equal strings.
Counting distinct strings is what a hash set does, so the answer is the size of the set of canonical forms.
Approach: Normalize, then count with a set
- Create an empty set
seen. - For each email, split it at '@' into
localanddomain. - Keep only the part of
localbefore the first '+', then remove every '.' from it. - Add
local + '@' + domaintoseen. - Return
len(seen).
Step-by-step example
emails = ["[email protected]", "[email protected]", "[email protected]"]
- "test.email+alex" loses "+alex" and its dot, giving [email protected]. The set has 1 entry.
- "test.e.mail+bob.cathy" loses "+bob.cathy" and two dots, giving [email protected] again. Already present, so the set stays at 1.
- "testemail+david" becomes testemail, and the domain lee.tcode.com keeps its dot. [email protected] is new, so the set has 2.
- Return 2.
Code: Python, Java, C++
1class Solution:
2 def numUniqueEmails(self, emails: List[str]) -> int:
3 seen = set()
4 for email in emails:
5 local, domain = email.split('@')
6 local = local.split('+')[0]
7 local = local.replace('.', '')
8 seen.add(local + '@' + domain)
9 return len(seen)1class Solution {
2 public int numUniqueEmails(String[] emails) {
3 Set<String> seen = new HashSet<>();
4 for (String email : emails) {
5 int at = email.indexOf('@');
6 String local = email.substring(0, at);
7 String domain = email.substring(at);
8 int plus = local.indexOf('+');
9 if (plus >= 0) local = local.substring(0, plus);
10 local = local.replace(".", "");
11 seen.add(local + domain);
12 }
13 return seen.size();
14 }
15}1class Solution {
2public:
3 int numUniqueEmails(vector<string>& emails) {
4 unordered_set<string> seen;
5 for (const string& email : emails) {
6 size_t at = email.find('@');
7 string local = email.substr(0, at);
8 string domain = email.substr(at);
9 size_t plus = local.find('+');
10 if (plus != string::npos) local = local.substr(0, plus);
11 local.erase(remove(local.begin(), local.end(), '.'), local.end());
12 seen.insert(local + domain);
13 }
14 return seen.size();
15 }
16};Time and space complexity
O(n * L)
Each of the n emails of length at most L is scanned a constant number of times, and hashing it costs O(L).
O(n * L)
The set can hold up to n canonical addresses of length up to L.
Other approaches
Single character scan (time O(n * L), space O(n * L))
Build the canonical form in one pass: skip dots, stop copying the local part at '+', jump to '@' and copy the domain. Same complexity, fewer temporary strings.
Sort the canonical forms (time O(n log n * L), space O(n * L))
Normalize every email, sort the list, and count positions where a value differs from its predecessor. Works without a hash set but adds a log factor.
Common mistakes
- Removing dots from the whole email. Dots in the domain are significant, so [email protected] and [email protected] are different inboxes.
- Cutting at the last '+' instead of the first. Everything after the first plus is ignored, including later plus signs.
- Dropping the '@' when joining local and domain. Without it, [email protected] and [email protected] both become abc.com and get merged by mistake.
- Counting distinct raw strings. Different spellings of the same inbox must be merged.
Frequently asked questions
Do the rules ever apply to the domain?
No. Both the dot rule and the plus rule apply only to the local name. The domain is compared exactly as written.
What if the local name ends with '+' and nothing after it?
The cut still happens at the '+', which simply removes the plus itself. [email protected] becomes [email protected].
Why not use a regular expression?
You can, but split and replace are clearer and avoid regex overhead. The logic is just two string operations on the local name.