Sponsored
Sponsored
In this approach, we'll use a set to store unique email addresses. We'll iterate over each email, split it into local and domain parts, then manipulate the local part by removing any characters after the first '+' and all periods '.' before rejoining with the domain. Finally, we'll add the standardized email to the set. The size of the set gives the count of unique emails.
Time Complexity: O(N * M) where N is the number of emails and M is the maximum length of an email address.
Space Complexity: O(N) due to the storage of unique emails in a set.
1#include <iostream>
2#include <vector>
3#include <unordered_set>
4
5using namespace std;
6
7int numUniqueEmails(vector<string>& emails) {
8 unordered_set<string> unique_emails;
9 for (string email : emails) {
10 int at_index = email.find('@');
11 string local = email.substr(0, at_index);
12 string domain = email.substr(at_index);
13 int plus_index = local.find('+');
14 if (plus_index != string::npos) {
15 local = local.substr(0, plus_index);
16 }
17 local.erase(remove(local.begin(), local.end(), '.'), local.end());
18 unique_emails.insert(local + domain);
19 }
20 return unique_emails.size();
21}
In C++, utilize an unordered_set to track unique emails. For each email, split around '@' to separate local and domain segments. Truncate the local part at '+' if present, and expunge all '.' characters. Then, recombine with domain and insert into the set. Return the set's size as the count of unique emails.
In this approach, instead of transforming emails directly using a set, we'll utilize arrays to manipulate the email parts. We'll maintain a boolean array for discovered unique emails and an index array to track up to where the email is unique. This efficient tracking helps us determine unique addresses without full storage, but more focused on transformations directly performed within the iteration loop.
Time Complexity: O(N * M), since per email processed once fully.
Space Complexity: O(N), enabling efficient tracking of unique addresses.
using System.Collections.Generic;
public class UniqueEmail
{
public int NumUniqueEmails(string[] emails)
{
HashSet<string> seenEmails = new HashSet<string>();
foreach (string email in emails)
{
var local = new System.Text.StringBuilder();
var domain = new System.Text.StringBuilder();
bool atSymbol = false, plusSymbol = false;
foreach (char c in email)
{
if (c == '@')
{
atSymbol = true;
}
if (atSymbol)
{
domain.Append(c);
}
else
{
if (c == '+')
{
plusSymbol = true;
}
else if (c != '.' && !plusSymbol)
{
local.Append(c);
}
}
}
seenEmails.Add(local.ToString() + domain.ToString());
}
return seenEmails.Count;
}
}
The C# approach here highlights an equivalent methodology without frequent string operations outside loop bodies, using StringBuilder for efficient adjustments and consistently including domain-related adjustments after local fixes.