Skip to content
Related Articles

Related Articles

Find the first repeated word in a string
  • Difficulty Level : Medium
  • Last Updated : 26 Feb, 2021

Given a string, Find the 1st repeated word in a string
Examples: 

Input : "Ravi had been saying that he had been there"
Output : had

Input : "Ravi had been saying that"
Output : No Repetition

Input : "he had had he"
Output : he

question source : https://www.geeksforgeeks.org/goldman-sachs-interview-experience-set-29-internship/

The idea is to tokenize the string and store each word and its count in hashmap. Then traverse the string again and for each word of string, check its count in created hashmap. 

CPP




// CPP program for finding first repeated
// word in a string
#include <bits/stdc++.h>
using namespace std;
 
// returns first repeated word
string findFirstRepeated(string s)
{
    // break string into tokens
    // and then each string into set
    // if a word appeared before appears
    // again, return the word and break
 
    istringstream iss(s);
    string token;
 
    // hashmap for storing word and its count
    // in sentence
    unordered_map<string, int> setOfWords;
 
    // store all the words of string
    // and the count of word in hashmap
 
    while (getline(iss, token, ' ')) {
        if (setOfWords.find(token) != setOfWords.end())            
            setOfWords[token] += 1;  // word exists
        else
            // insert new word to set
            setOfWords.insert(make_pair(token, 1));       
    }
 
    // traverse again from first word of string s
    // to check if count of word is greater than 1
 
    // either take a new stream or store the words
    // in vector of strings in previous loop
    istringstream iss2(s);
    while (getline(iss2, token, ' ')) {
        int count = setOfWords[token];
        if (count > 1) {
            return token;
        }
    }
 
    return "NoRepetition";
}
 
// driver program
int main()
{
    string s("Ravi had been saying that he had been there");
    string firstWord = findFirstRepeated(s);
    if (firstWord != "NoRepetition")
        cout << "First repeated word :: "
             << firstWord << endl;
    else
        cout << "No Repetitionn";
    return 0;
}


Output

First repeated word :: had

Method #2: Using built in python functions:

  • As all the words in a sentence are separated by spaces.
  • We have to split the sentence by spaces using split().
  • We split all the words by spaces and store them in a list.
  • Use Counter function to count frequency of words
  • Traverse the list and check if any word has frequency greater than 1
  • If it is present then print the word and break the loop

Below is the implementation:



Python3




# Python program for the above approach
from collections import Counter
 
# Python program to find the first
# repeated character in a string
def firstRepeatedWord(sentence):
 
    # spliting the string
    lis = list(sentence.split(" "))
     
    # Calculating frequency of every word
    frequency = Counter(lis)
     
    # Traversing the list of words
    for i in lis:
       
        # checking if frequency is greater than 1
         
        if(frequency[i] > 1):
            # return the word
            return i
 
 
# Driver code
sentence = "Vikram had been saying that he had been there"
print(firstRepeatedWord(sentence))
# this code is contributed by vikkycirus


Output

had

This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :