Find the first repeated word in a string - GeeksforGeeks

22 Apr, 2022
Given a string, Find the 1st repeated word in a stringExamples: 
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/
Simple Approach : Start iterating from back and for every new word , store it in unordered map . For every word which has occurred more than one  , update ans to be that word , at last reverse ans and print it.
C++
Python3
Javascript
// Cpp program to find first repeated word in a string#include<bits/stdc++.h>using namespace std;void solve(string s){    unordered_map<string,int> mp;  // to store occurrences of word    string t="",ans="";    // traversing from back makes sure that we get the word which repeats first as ans    for(int i=s.length()-1;i>=0;i--)    {        // if char present , then add that in temp word string t        if(s[i]!=' ')        {            t+=s[i];                     }        // if space is there then this word t needs to stored in map        else        {            mp[t]++;            // if that string t has occurred previously then it is a possible ans            if(mp[t]>1)               ans=t;            // set t as empty for again new word              t="";                     }    }         // first word like "he" needs to be mapped            mp[t]++;            if(mp[t]>1)               ans=t;                               if(ans!="")    {        // reverse ans string as it has characters in reverse order        reverse(ans.begin(),ans.end());        cout<<ans<<'\n';    }    else    cout<<"No Repetition\n";}int main(){    string u="Ravi had been saying that he had been there";    string v="Ravi had been saying that";    string w="he had had he";    solve(u);    solve(v);    solve(w);              return 0;     }
# Python program to find first repeated word in a stringdef solve(s):     mp = {} # to store occurrences of word    t = ""    ans = ""         # traversing from back makes sure that we get the word which repeats first as ans    for i in range(len(s) - 1,-1,-1):               # if char present , then add that in temp word string t        if(s[i] != ' '):            t += s[i]                 # if space is there then this word t needs to stored in map        else:                     # if that string t has occurred previously then it is a possible ans            if(t in mp):                ans = t            else:                mp[t] = 1                         # set t as empty for again new word            t = ""                 # first word like "he" needs to be mapped    if(t in mp):        ans=t                             if(ans!=""):         # reverse ans string as it has characters in reverse order        ans = ans[::-1]        print(ans)    else:        print("No Repetition") # driver codeu = "Ravi had been saying that he had been there"v = "Ravi had been saying that"w = "he had had he"solve(u)solve(v)solve(w) # This code is contributed by shinjanpatra
<script>// JavaScript program to find first repeated word in a string function solve(s){    let mp = new Map();  // to store occurrences of word    let t = "";    let ans = "";         // traversing from back makes sure that we get the word which repeats first as ans    for(let i = s.length - 1; i >= 0; i--)    {        // if char present , then add that in temp word string t        if(s[i] != ' ')        {            t += s[i];                     }                 // if space is there then this word t needs to stored in map        else        {                     // if that string t has occurred previously then it is a possible ans            if(mp.has(t))               ans = t;            else mp.set(t, 1)                         // set t as empty for again new word              t = "";                     }    }         // first word like "he" needs to be mapped    if(mp.has(t)) ans=t;                               if(ans!="")    {        // reverse ans string as it has characters in reverse order        ans = [...ans].reverse().join("");        document.write(ans);    }    else    document.write("No Repetition");} // driver codeconst u = "Ravi had been saying that he had been there";const v = "Ravi had been saying that";const w = "he had had he";solve(u);solve(v);solve(w); // This code is contributed by shinjanpatra</script>
had
No Repetition
he
  
Another Approach: 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
Java
// CPP program for finding first repeated// word in a string#include <bits/stdc++.h>using namespace std; // returns first repeated wordstring 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 programint 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;}
// Java program for finding first repeated// word in a stringimport java.util.*; class GFG{         // returns first repeated word    static 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             String token[] = s.split(" ");             // hashmap for storing word and its count        // in sentence        HashMap<String, Integer> setOfWords = new HashMap<String, Integer>();             // store all the words of string        // and the count of word in hashmap             for (int i=0; i<token.length; i++) {            if (setOfWords.containsKey(token[i]))                           setOfWords.put(token[i], setOfWords.get(token[i]) + 1); // word exists            else                // insert new word to set                setOfWords.put(token[i], 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        for (int i=0; i<token.length; i++) {            int count = setOfWords.get(token[i]);            if (count > 1) {                return token[i];            }        }             return "NoRepetition";    }         // driver program    public static void main(String args[])    {        String s = "Ravi had been saying that he had been there";        String firstWord = findFirstRepeated(s);        if (!firstWord.equals("NoRepetition"))            System.out.println("First repeated word :: " + firstWord);        else            System.out.println("No Repetitionn");    }}
First repeated word :: had
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 approachfrom collections import Counter # Python program to find the first# repeated character in a stringdef firstRepeatedWord(sentence):     # splitting 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 codesentence = "Vikram had been saying that he had been there"print(firstRepeatedWord(sentence))# this code is contributed by vikkycirus
had
Instead of counting a number of occurrences of each word which will have O(N) time and space complexity, where N is number of words, we can stop when the count of any word becomes 2. That is no need to iterate through all the words in string.
Let’s say our first repeated word is present at Mth index, then
By using this approach, space and time complexity reduced from O(N) to O(M).
Where,
N: number of words in a string.
M: Index at which first repeating word is present
However, Worst case( When no word is being repeated or the word being repeated is present at last) time and space complexity will still be O(N).
Steps:
Create a default dictionary with an initial value of 0, to keep track count of words.
Iterate through each word in a sentence and increment the count of that word by 1.
If (count of the word) > 1, return the word.
If the count of none of the words is greater than 1 then that is we are outside our loop then return “No word is being repeated”.
Python3
Javascript
# Import defaultdict from Collections modulefrom collections import defaultdict def first_repeating_word(s):     # Creating a defaultdict with    # default values as 0.    # Every word will have an    # initial count of 0    word_count = defaultdict(lambda: 0)     # Iterating through all words in string.    for i in s.split():         # Increment the word count of        # the word we encounter by 1        word_count[i] += 1         # If word_count of current word        # is more than 1, we got our answer, return it.        if word_count[i] > 1:            return i     # If program has reached here that    # means no word is being repeated    return 'No word is being repeated'  # Driver Codeif __name__ == '__main__':    s = "Ravi had been saying that he had been there"    print(first_repeating_word(s))     # This code is contributed by Anurag Mishra
<script> function first_repeating_word(s){     // Creating a defaultdict with    // default values as 0.    // Every word will have an    // initial count of 0    let word_count = new Map()     // Iterating through all words in string.    for(let i of s.split(' ')){         // Increment the word count of        // the word we encounter by 1        if(word_count.has(i)){            word_count.set(i,word_count.get(i) + 1);        }        else word_count.set(i,1);         // If word_count of current word        // is more than 1, we got our answer, return it.        if(word_count.get(i) > 1)            return i    }     // If program has reached here that    // means no word is being repeated    return 'No word is being repeated'} // Driver Codelet s = "Ravi had been saying that he had been there"document.write(first_repeating_word(s)) // This code is contributed by shinjanpatra </script>
had
Time complexity: O(M)
Space Complexity: O(M)
Instead of counting a number of occurrences of each word which will have O(N) time and space complexity, where N is a number of words, we can just store words in a HashSet, and as soon as we reach a word that is already present in the HashSet we can return.
C++
Java
// CPP program for finding first repeated// word in a string#include <bits/stdc++.h>using namespace std; // returns first repeated wordstring 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;     // hashset for storing word and its count    // in sentence    set<string> setOfWords;     // store all the words of string    // and the count of word in hashset     while (getline(iss, token, ' ')) {        // if word exists return        if (setOfWords.find(token) != setOfWords.end()) {            return token;        }         // insert new word to set        setOfWords.insert(token);    }     return "NoRepetition";} // driver programint 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;}
// Java program for finding first repeated// word in a stringimport java.util.*; public class GFG{         // returns first repeated word    static String findFirstRepeated(String s)    {        // break string into tokens        String token[] = s.split(" ");                 // hashset for storing words        HashSet<String> set = new HashSet<String>();                 // store the words of string in hashset        for(int i=0; i<token.length; i++){                         // if word exists return            if(set.contains(token[i])){                return token[i];            }                         // insert new word to set            set.add(token[i]);        }             return "NoRepetition";    }         // driver program    public static void main(String args[])    {        String s = "Ravi had been saying that he had been there";        String firstWord = findFirstRepeated(s);        if (!firstWord.equals("NoRepetition"))            System.out.println("First repeated word :: " + firstWord);        else            System.out.println("No Repetitionn");    }}
First repeated word :: 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. 
vikkycirus
anurag2311
adityapande88
nayanmanojgupta
varshagumber28
shinjanpatra
surinderdawra388
rkbhola5
Amazon
cpp-stringstream
cpp-unordered_map
Goldman Sachs
Strings
Amazon
Goldman Sachs
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different methods to reverse a string in C/C++
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Array of Strings in C++ (5 Different Ways to Create)
Reverse words in a given string
Top 50 String Coding Problems for Interviews