DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on • Edited on

Leetcode - 929. Unique Email Addresses

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];
Enter fullscreen mode Exit fullscreen mode

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];
}

Enter fullscreen mode Exit fullscreen mode

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
  }

Enter fullscreen mode Exit fullscreen mode

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;
};

Enter fullscreen mode Exit fullscreen mode

Please do follow the series if you are struggling with leetcode questions šŸ˜‡

Top comments (0)