Consider an array of string and find duplicate words in that array and print that duplicate words if exist. Examples:
Input : { "welcome", "to", "geeks", "for", "geeks" }
Output : geeks
Input : { "reduce", "reuse", "recycle", "reduce",
"reuse", "recycle", " recycle" }
Output : recycle
reduce
reuse
Input : { "Go", "Green" }
Output : No Duplicate words
Method 1 (Using Sorting) 1. Sort array of string. 2. compare adjacent word in array of string. 3. if two word are same then push that word in another vector string. 4. print the duplicate words if exist.
CPP
#include <bits/stdc++.h>
using namespace std;
void printDuplicates(vector<string> words)
{
vector<string> duplicate;
sort(words.begin(), words.end());
for (int i = 1; i < words.size(); i++) {
if (words[i - 1] == words[i]) {
if (duplicate.empty())
duplicate.push_back(words[i]);
else if (words[i] != duplicate.back())
duplicate.push_back(words[i]);
}
}
if (duplicate.size() == 0)
cout << "No Duplicate words" << endl;
else
for (int i = 0; i < duplicate.size(); i++)
cout << duplicate[i] << endl;
}
int main()
{
vector<string> words{ "welcome", "to", "geeks", "for",
"geeks", "to", "geeks" };
printDuplicates(words);
return 0;
}
Method 2 (Using Hashing) 1. Create an empty hash table. 2. One by one traverse words. 3. For every word check if already exists in the hash. ……..if (already exists in hash) ………….Print the word ……..Else ………….Insert the word in hash.
CPP
#include<bits/stdc++.h>
using namespace std;
void printDuplicates(vector<string> words)
{
unordered_set<string> s;
bool dupFound = false;
for (int i = 1; i<words.size(); i++)
{
if (s.find(words[i]) != s.end())
{
cout << words[i] << endl;
dupFound = true;
}
else
s.insert(words[i]);
}
if (dupFound == false)
cout << "No Duplicate words" << endl;
}
int main()
{
vector<string>words{ "welcome", "to", "geeks",
"for", "geeks" };
printDuplicates(words);
return 0;
}
Output:
geeks
Learn to code easily with our course
Coding for Everyone . This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
25 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...