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 '+'.

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.

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.

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 emails[i], return the number of different addresses that actually receive mails.

Input: emails = ["user.jc@cscode.io","u.s.e.r.jc+test@cscode.io","user.jc+test@cs.code.io"]
Output: 2
Explanation: "user.jc@cscode.io" and "u.s.e.r.jc+test@cscode.io" will become "userjc@cscode.io" after you ignore "." and all characters after "+" symbol. and "user.jc+test@cs.code.io" will become "userjc@cs.code.io" which has different domain name.

Contents

In this approach, we are going to first apply rules given in the problem statement, then store resultant email addresses in a HashSet and return the size of it.

Rules given are:

import java.util.HashSet; public class UniqueEmailAddresses { static int filterUniqueEmailAddressesUsingHashing(String[] emails) { HashSet<String> unique = new HashSet<>(); for(String email: emails) { StringBuilder sb = new StringBuilder(email.length()); int i=0; while(i<email.length()) { char c = email.charAt(i); if(c == '+' || c == '@') { int index = email.indexOf('@', i); sb.append(email.substring(index)); break; } if(c != '.'){ sb.append(c); } i++; } unique.add(sb.toString()); } return unique.size(); } }
Complexity Analysis:

Time complexity: Above code runs in O(n * m) time where n is the input array emails length and m is the average size of email string. This is because, we are looping through emails array, then each character of email address.
Space complexity: O(n).

Above implementations source code can be found at GitHub link for Java code