Unique Email Addresses Solution in Python

Explore More Solutions

Code Solution


class Solution:
    def numUniqueEmails(self, emails: list[str]) -> int:
        seen = set()

        for email in emails:
            local, domain = email.split('@')
            local = local.split('+')[0].replace('.', '')
            seen.add(local + '@' + domain)

        return len(seen)

Problem Description

Ah, the classic dilemma of email addresses! You know, the one where you think you’ve got a unique email, but then you realize that your friend Bob has been using the same one with a few dots and a sneaky plus sign? Welcome to the world of Unique Email Addresses!

In this LeetCode problem, you’re tasked with counting how many unique email addresses are actually valid. The catch? Emails can have dots in the local part (the part before the @) that are ignored, and anything after a plus sign is also ignored. So, if Bob sends an email to bob@example.com, b.o.b@example.com, and bob+spam@example.com, they all land in the same inbox.

Imagine if life worked like that! You could just add a dot or a plus to your name and avoid all those awkward conversations. “Oh, you sent me an email? I didn’t see it because it went to my ‘spam’ folder!”

Approach

The solution involves splitting each email into its local and domain parts. The local part is then processed to remove any dots and anything after a plus sign. Finally, we store the unique combinations of local and domain parts in a set, which inherently handles duplicates for us. The length of this set gives us the count of unique emails.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(N), where N is the number of emails.
Space Complexity O(N) in the worst case, where all emails are unique.

Real-World Example

Let’s say you’re trying to sign up for a newsletter, but you keep getting spammed because you used different variations of your email. You might have john.doe@gmail.com, johndoe@gmail.com, and john.doe+news@gmail.com. In reality, they all point to the same inbox, but the newsletter thinks you’re three different people! This problem helps you figure out how many unique addresses you actually have, so you can avoid that spammy mess.

Similar Problems

If you enjoyed this problem, you might also like:

  • 3-Sum Solution in Python