Unique Email Addresses
Every valid email consists of a local name and a domain name, separated by the '@''.''+'
-
For example, in
,"alice@cscode.io" is the local name, and"alice" is the domain name."cscode.io"
If you add periods '.'
-
For example,
and"alice.z@cscode.io" forward to the same email address."alicez@cscode.io"
If you add a plus '+'
-
For example,
will be forwarded to"m.y+name@email.com" ."my@email.com"
It is possible to use both of these rules at the same time.
Given an array of strings emailsemails[i]
Example 1
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.
Solution using HashSet, after applying rules
In this approach, we are going to first apply rules given in the problem statement, then store resultant email addresses in a HashSet
Rules given are:
-
If the email's local name part, ignore
symbols, if there are any.'.' -
In the email's local name part, ignore all characters after
symbol, if it is there.'+' -
In the email address, take all characters after
symbol.'@'
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 nemailsmemails
Space complexity: O(n).
Above implementations source code can be found at