Check duplicates in a stream of strings
Last Updated :
01 Aug, 2022
Given an array arr[] of strings containing the names of employees in a company. Assuming that the names are being entered into a system one after another, the task is to check whether the current name is entered for the first time or not.
Examples:
Input: arr[] = {“geeks”, “for”, “geeks”}
Output:
No
No
Yes
Input: arr[] = {“abc”, “aaa”, “cba”}
Output:
No
No
No
Approach: Create an unordered_set to store the names of the employees and start traversing the array, if the current name is already present in the set then print Yes else print No and insert it into the set.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void insertNames(string arr[], int n)
{
unordered_set<string> set;
for ( int i = 0; i < n; i++) {
if (set.find(arr[i]) == set.end()) {
cout << "No\n" ;
set.insert(arr[i]);
}
else {
cout << "Yes\n" ;
}
}
}
int main()
{
string arr[] = { "geeks" , "for" , "geeks" };
int n = sizeof (arr) / sizeof (string);
insertNames(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void insertNames(String arr[], int n)
{
HashSet<String> set = new HashSet<String>();
for ( int i = 0 ; i < n; i++)
{
if (!set.contains(arr[i]))
{
System.out.print( "No\n" );
set.add(arr[i]);
}
else
{
System.out.print( "Yes\n" );
}
}
}
public static void main(String[] args)
{
String arr[] = { "geeks" , "for" , "geeks" };
int n = arr.length;
insertNames(arr, n);
}
}
|
Python3
def insertNames(arr, n) :
string = set ();
for i in range (n) :
if arr[i] not in string :
print ( "No" );
string.add(arr[i]);
else :
print ( "Yes" );
if __name__ = = "__main__" :
arr = [ "geeks" , "for" , "geeks" ];
n = len (arr);
insertNames(arr, n);
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void insertNames(String []arr, int n)
{
HashSet<String> set = new HashSet<String>();
for ( int i = 0; i < n; i++)
{
if (! set .Contains(arr[i]))
{
Console.Write( "No\n" );
set .Add(arr[i]);
}
else
{
Console.Write( "Yes\n" );
}
}
}
public static void Main(String[] args)
{
String []arr = { "geeks" , "for" , "geeks" };
int n = arr.Length;
insertNames(arr, n);
}
}
|
Javascript
<script>
function insertNames(arr, n)
{
let set = new Set();
for (let i = 0; i < n; i++)
{
if (!set.has(arr[i]))
{
document.write( "No" + "<br/>" );
set.add(arr[i]);
}
else
{
document.write( "Yes" + "<br/>" );
}
}
}
let arr = [ "geeks" , "for" , "geeks" ];
let n = arr.length;
insertNames(arr, n);
</script>
|
Time Complexity: O(n), Where n is the length of the given string array.
Auxiliary Space: O(n), To store the names of the employees in a set.
Share your thoughts in the comments
Please Login to comment...