Find the first repeated word in a string in C++

C++Server Side ProgrammingProgramming

In this problem, we are a string str consisting of comma separated words. Our task is to find the first repeated word in a string.

We need to find the first word 'string between two spaces' which gets repeated in the string.

Let's take an example to understand the problem,

Input : str = "C program are easy to program"
Output : program

Solution Approach

A simple solution to the problem is using hashmap data structure. To find the first repeated word, we will store each word and its count (number of times it appeared in the string ) in the hashmap. For this we will keep checking if the current word is present or not.

Then we will print the first work with more than one occurrence count in the hashmap.


Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
string findFirstRepeatWord(string str){
   istringstream iss(str);
   string word;
   unordered_map<string, int> wordCountMap;
   while (getline(iss, word, ' ')) {
      if (wordCountMap.find(word) != wordCountMap.end())
         wordCountMap[word] ++;
         wordCountMap.insert(make_pair(word, 1));
   istringstream iss2(str);
   while (getline(iss2, word, ' ')) {
      int count = wordCountMap[word];
      if (count > 1) {
         return word;
   return "NoRepetition";
int main(){
   string str = "C program are easy to program";
   string repeatedWord = findFirstRepeatWord(str);
   if (repeatedWord != "NoRepetition")
      cout<<"The first repeated word is '"<<repeatedWord<<"'";
      cout<<"No word is Repeated in the string";
   return 0;


The first repeated word is 'program'

This program uses a lot of in-build functions for making the task easier.

Updated on 27-Jan-2022 10:50:35