Lets quickly go into the solution for the unique email addresses problem
we can see every email in localName + @ + domainName this form
let localName = email.split('@')[0] ?? '';
const domainName = email.split('@')[1];
And the question tells if localName has + sign in it we need to ignore the rest of the characters after it , example "m.y+name@email.com" is equal to "m.y@email.com"
if (localName.includes('+')) {
localName = localName.split('+')?.[0];
}
Also the question tells us that if we have . in email then it is considered as forwardable to the email , after replacing . (dot) with '' empty character
if (localName.includes('.') || domainName.includes('.')) {
isForwardable = true;
localName = localName.replace(/\./g, '');
}
if (isForwardable) {
return localName + '@' + domainName; //returning email
} else {
return ''; //returning empty string if not forwardible
}
Complete code
/**
* @param {string[]} emails
* @return {number}
*/
const convertEmail = email => {
let localName = email.split('@')[0] ?? '';
const domainName = email.split('@')[1];
let isForwardable = false;
if (localName.includes('+')) {
localName = localName.split('+')?.[0];
}
if (localName.includes('.') || domainName.includes('.')) {
isForwardable = true;
localName = localName.replace(/\./g, '');
}
if (isForwardable) {
return localName + '@' + domainName;
} else {
return '';
}
};
var numUniqueEmails = function(emails) {
let uniqueEmails = new Set();
emails.forEach(email => {
const convertedEmail = convertEmail(email);
if (convertedEmail !== '') {
uniqueEmails.add(convertedEmail);
}
});
return uniqueEmails.size;
};
Please do follow the series if you are struggling with leetcode questions š
Top comments (0)