Tuesday, March 23, 2021

[Google Question] Unique Email Addresses

Problem: Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.

For example, in "abc@xyz.com", "abc" is the local name, and "xyz.com" is the domain name.

If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.

For example, "abc.d@xyz.com" and "abcd@xyz.com" forward to the same email address.

If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.

For example, "ab.c+lmn@xyz.com" will be forwarded to "abc@xyz.com".

It is possible to use both of these rules at the same time.

Given an array of strings emails where we send one email to each email[i], return the number of different addresses that actually receive mails.

Example:

Input: emails = ["abc.d+lmn@xyz.com","ab.c.d+lmn.pqr@xyz.com","abcd+pqr@xy.z.com"]
Output: 2
Explanation: "abcd@lxyz.com" and "abcd@xy.z.com" actually receive mails.


Approach: We can remove all the characters from local name which comes after the '+' and also we can replace all '.' with empty string on all the input strings.

We can add the result of the above operations in a HashSet and in the end we can just return the count of hashset.


Implementation in C#:

    public int NumUniqueEmails(string[] emails) 

    {

        int length = emails?.Length ?? 0;

        HashSet<string> uniqueEmailAddressSet = new HashSet<string>();

        for(int i = 0; i < length; ++i)

        {

            string[] names = emails[i].Split('@');

            string localName = names[0];

            string domainName = names[1];

            int index = localName.IndexOf('+');

            if (index != -1)

            {

                localName = localName.Substring(0, index);

            }

            localName = localName.Replace(".", "");

            uniqueEmailAddressSet.Add(localName + "@" + domainName);

        }

        return uniqueEmailAddressSet.Count;

    }


Complexity: O(n) where is n is the number of characters in the input string array

No comments:

Post a Comment