HackerRank Detect the Email Addresses Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Detect the Email Addresses Solution. This problem is a part of the Regex HackerRank Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the  Regex HackerRank Solutions using  CPP, JAVA, PYTHON, JavaScript & PHP Programming Languages.

HackerRank Detect the Email Addresses Solution
HackerRank Detect the Email Addresses Solution

HackerRank Detect the Email Addresses Solution


You will be provided with a block of text, spanning not more than hundred lines. Your task is to find the unique e-mail addresses present in the text. You could use Regular Expressions to simplify your task. And remember that the “@” sign can be used for a variety of purposes! Requirements are simplified versus real world. There can be a number of strings separated by dots before and after the “@” symbol. Strings will be made up of characters in the ranges a-z, A-Z, 09, _ (underscore).

Input Format

The first line contains an integer N (N<=100), which is the number of lines present in the text fragment which follows.
From the second line, begins the text fragment (of N lines) in which you need to search for e-mail addresses.

Output Format

All the unique e-mail addresses detected by you, in one line, in lexicographical order, with a semi-colon as the delimiter.

Sample Input

HackerRank is more than just a company
We are a tight group of hackers, bootstrappers, entrepreneurial thinkers and innovators. We are building an engaged community of problem solvers. Imagine the intelligence and value that a room would hold if it contained hackers/problem solvers from around the world? We’re building this online.
Hypothesis: Every hacker loves a particular type of challenge presented in a certain set of difficulty. If we build a large collection of real world challenges in different domains with an engaging interface, it is going to be incredible! Join us to create history.
Available Positions
Product Hacker product@hackerrank.com
Challenge Curator
Product Evangelist
Product Designer
Content Creator
ACM World Finals Hacker
Backend C++ Hacker
Mail us at hackers@hackerrank.com to chat more. Or you can write to us at interviewstreet@hackerrank.com!
Working for a startup is hard work, but there are plenty of benefits of working for a small, fun, growing team.
[Image] Perk: Get tools for the jobAll the Right ToolsWe know that everyone’s perfect workspace is unique to them. We will get you set up with whatever equipment you need to start hacking – a new 15” Macbook Pro or iMac, or a computer of your choice plus a display if you need it. Additionally, if you require any software or other tools, we’ve got it covered.[Image] Perk: Flexible HoursFlexible HoursBecause we work so hard, we encourage our employees to keep flexible hours and don’t require them to track their time. A morning scrum and open communication ensures that the job gets done on time, and we rely on the honor system so that you can work on your own pace.[Image] Perk: HealthcareWellness SupportTo work hard, you have to be healthy. We will cover your health, dental, and visual insurance with no wait period. That means instant benefits from the day you’re hired.[Image] Perk: Choice of LocationLocation, Location, LocationWe are the first Indian company to be backed by Y-Combinator, and as a result we have a thriving office in Bangalore and a growing office in Mountain View, CA. Depending on your residency or visa status, we will get you situated in one of our two offices, both of which are located in the heart of their country’s tech industry.[Image] Perk: Choice of LocationCreative SupportIf you have a cool side project that you want to launch, we will pay for EC2/heroku servers to get it off the ground. Side projects fuel creativity and learning, which are crucial to the HackerRank culture.
The culture of a startup is reflective of the founders’ DNA. Larry Page & Sergey Brin were PhD’s from Stanford and that’s why Google is filled with high scoring graders from top schools and is very hard to get in if you’re not a CS major. Similarly, the hacker culture at Facebook is inspired by Zuckerberg, a hacker, the design culture by Steve Jobs and so on.
The adjective to describe the environment/founders here is relentless hardworkers. It might be a general trait of a startup but I’m pretty sure it’s a notch higher here and defines the culture. This is what has taken us this far. It’s not working in weekends or allnighters that count, but the effort that goes into building something intellectually engaging for hackers and making it fun is high.
You’ll have to embrace randomness and chaos. There’s some level of discipline (eg: daily scrums) but only so much. We push boundaries everyday, stretch our limits but no one complains because there’s a feeling of doing something great at the end of the day, every single day.

Sample Output


HackerRank Detect the Email Addresses Solution in Cpp

#include <cmath>
#include <cstdio>
#include <vector>
#include <set>
#include <iostream>
#include <algorithm>
using namespace std;

vector<string> split(string s, char delimiter){
    vector<string> result;
    string t = "";
    for(int i = 0; i < s.length(); i++){
        if(s[i] == delimiter || s[i] == '\t'){
            if(t!="") {
        else {
    if(t!="") result.push_back(t);
    return result;

bool isEmail(string s){
    bool email = false;
    int i = 0;
    int len = s.length();
    while(i < len && s[i]!='@')i++;
    if(i!=len) {
        if(i < len && s[i] != '.') {
            while(i < len && s[i]!='.') i++;
               email = true;
    return email;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    int n;
    string s;
    set<string> emails;
        vector<string> spt = split(s,' ');
        for(int i = 0; i < spt.size(); i++){
            if(isEmail(spt[i])) {
                int j;
                for(j = spt[i].length() - 1; j>=0; j--) {
                    if(spt[i][j] != '.' && spt[i][j] != '!') break; 
    string result = "";
    for(set<string>::iterator it = emails.begin(); it != emails.end(); it++){
        result+= *it + ";";
    cout<<result.substr(0,result.length() -1)<<endl;
    return 0;

HackerRank Detect the Email Addresses Solution in Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

 * @author Antonio081014
 * @since Sep 19, 2013, 3:46:51 PM
public class Solution {

	public static void main(String[] args) {
		Solution main = new Solution();

	private void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
			HashSet<String> emails = new HashSet<String>();
			int N = Integer.parseInt(in.readLine());

			for (int i = 0; i < N; i++) {
				String[] s = in.readLine().split("\\s");
				for (int j = 0; j < s.length; j++) {
					// s[j] = s[j].replaceAll("[^a-zA-Z0-9@.]", "");
					if (isEmail(s[j])) {
						// s[j].replaceAll("(\\b)[\\W]*", "");
						s[j] = trans(s[j]);
			ArrayList<String> list = new ArrayList<String>(emails);
			for (int i = 1; i < list.size(); i++)
				System.out.print(";" + list.get(i));
		} catch (Exception e) {

	private boolean isEmail(String s) {
		// String pattern = "^(\\w)+@(\\w)+.(\\w)+[\\W]*";
		// String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
		// + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		// Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile(
		// "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$",
		Pattern pattern = Pattern
		Matcher matcher = pattern.matcher(s);
		return matcher.find();
		// return s.matches(EMAIL_PATTERN);

	private String trans(String s) {
		for (int i = s.length() - 1; i >= 0; i--) {
			if ((s.charAt(i) >= 'a' && s.charAt(i) <= 'z')
					|| (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
					|| (s.charAt(i) >= '0' && s.charAt(i) <= '9')) {
				return s.substring(0, i + 1);
			} else {
		return "";

HackerRank Detect the Email Addresses Solution in Python

import sys,re
for _ in range(tc):
for line in lines:
    for email in emails:
for e in sorted(emailIds):
print s[:-1]

HackerRank Detect the Email Addresses Solution in JavaScript

function processData(input) {
    var match = input.match(/(([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4}))((;(([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})))*)(;{0,1})/gi);
        var str = [];
        for(var i = 0; i < match.length; i++){
            if(str.indexOf(match[i]) == -1){
        return 0;

_input = "";
process.stdin.on("data", function (input) {
    _input += input;

process.stdin.on("end", function () {

HackerRank Detect the Email Addresses Solution in PHP

    $f = fopen("php://stdin", "r");
    $numLines = fgets( $f );
    $total = "";
    while( $line = fgets( $f ) ) $total .= $line;

    $matches = array();
    preg_match_all( '/\b[a-z_-]+[\.a-z_-]+?@[a-z_-]+\.[a-z_-]+[\.a-z_-]+?\b/siU', $total, $matches );
    asort( $matches[ 0 ] );
    $colon = "";
    foreach( array_unique( $matches[ 0 ] ) as $match )
        print $colon . $match;
        $colon =";";

Disclaimer: This problem (Detect the Email Addresses) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

Sharing Is Caring

Leave a Comment