Find lexicographically first ID of each domain from given Array of email IDs – GeeksforGeeks

Improve Article

Save Article

Like article

Improve Article

Save Article

You are given an array of Email IDs, the task is to return the lexicographically first email ID of each single domain.

Examples:

input: Emails[] = {“ajay@gmail.com”, “rahul@hotmail.com”, “saif@gmail.com”, “faheem@yahoo.com”, “sam@hotmail.com”}
Output: {“ajay@gmail.com”, “rahul@hotmail.com”, “faheem@yahoo.com”}
Explanation: All email IDs are of the total of 3 email domains in the input array so the output contains alphabetically the first email ID of each domain.

input: Emails[] = {“ben@gmail.com”, “alex@gmail.com”, “fin@gmail.com”, “zeke@gmail.com”}
Output: {“alex@gmail.com”}
Explanation: Every email ID is of only one domain ie “gmail” so the email which is alphabetically first among all is returned.

Approach: Implement the idea below to solve the problem:

The idea is to sort the input emails first and then iterate over the input email. For every single email extract its domain name and map it with entire email address using a hashmap and while iterating check whether any email of current email Id’s domain is present or not. If no such email Id is present in hashmap then insert the current email Id.

Follow the steps mentioned below to implement the idea:

  • Sort the Input Array and declare a hashmap that will have a string as key and value.
  • Iterate over the array and check whether the current email’s domain is present in the hashmap or not.
    • If yes then do nothing.
    • Otherwise, insert the current email ID into the hashmap along with its domain name.
  • Iterate over the Hashmap and populate the output array with its values.

Below is the implementation of the above approach.

C++

 

#include <bits/stdc++.h>

using namespace std;

 

void sendMail(string Emails[], int n)

{

    map<string, string> mp;

    

    sort(Emails, Emails + n);

 

    for (int i = 0; i < n; i++) {

        string temp = Emails[i];

 

        

        

        

        int place = temp.find('@');

 

        

        string domain = temp.substr(place);

 

        

        

        if (!mp.count(domain)) {

            mp[domain] = temp;

        }

    }

 

    

    

    for (auto it = mp.begin(); it != mp.end(); it++) {

        cout << it->second << endl;

    }

}

 

int main()

{

    int N = 5;

    string Emails[]

        = { "ajay@gmail.com", "rahul@hotmail.com",

            "saif@gmail.com", "faheem@yahoo.com",

            "sam@hotmail.com" };

 

    

    sendMail(Emails, N);

 

    return 0;

}

Output

ajay@gmail.com
rahul@hotmail.com
faheem@yahoo.com

Time Complexity: O(N)
Auxiliary Space: O(N)

Related articles:

Source link

5 thoughts on “Find lexicographically first ID of each domain from given Array of email IDs – GeeksforGeeks”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top