Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Find the first maximum length even word from a string
Next article icon

Find the first repeated word in a string

Last Updated : 20 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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”
he

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

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
 

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.

Implementation:

C++




// 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;
     
}
 
 

Java




import java.util.*;
 
public class GFG {
  // Java  program to find first repeated word in a string
  public static void solve(String s)
  {
    HashMap<String, Integer> mp
      = new HashMap<String,
    Integer>(); // to store
    // occurrences of word
    String t = "";
    String 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.charAt(i) != ' ') {
        t += s.charAt(i);
      }
      // if space is there then this word t needs to
      // stored in map
      else {
        if (!mp.containsKey(t)) {
          mp.put(t, 1);
        }
        else {
          mp.put(t, mp.get(t) + 1);
        }
 
        // if that string t has occurred previously
        // then it is a possible ans
        if (mp.get(t) > 1) {
          ans = t;
        }
        // set t as empty for again new word
        t = "";
      }
    }
 
    // first word like "he" needs to be mapped
    if (!mp.containsKey(t)) {
      mp.put(t, 1);
    }
    else {
      mp.put(t, mp.get(t) + 1);
    }
    if (mp.get(t) > 1) {
      ans = t;
    }
 
    if (!ans.equals("")) {
      // reverse ans string as it has characters in
      // reverse order
      StringBuilder input1 = new StringBuilder();
 
      // append a string into StringBuilder input1
      input1.append(ans);
 
      // reverse StringBuilder input1
      input1.reverse();
 
      System.out.println(input1);
    }
    else {
      System.out.print("No Repetition\n");
    }
  }
  public static void main(String[] args)
  {
    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);
  }
}
 
// This code is contributed by Aarti_Rathi
 
 

Python3




# Python program to find first repeated word in a string
def 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 code
u = "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
 
 

C#




// C# program to find first repeated word in a string
using System;
using System.Collections.Generic;
 
class GFG {
  static void solve(string s)
  {
    Dictionary<string, int> mp = new Dictionary<
      string, int>(); // to store occurrences of word
    string t = "";
    string 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 {
        if (mp.ContainsKey(t)) {
          mp[t] += 1;
        }
        else {
          mp.Add(t, 1);
        }
        // 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
    if (mp.ContainsKey(t)) {
      mp[t] += 1;
    }
    else {
      mp.Add(t, 1);
    }
 
    if (mp[t] > 1) {
      ans = t;
    }
 
    if (ans != "") {
      // reverse ans string as it has characters in
      // reverse order
      char[] charArray = ans.ToCharArray();
      Array.Reverse(charArray);
      Console.WriteLine(new string(charArray));
    }
    else {
      Console.Write("No Repetition\n");
    }
  }
  public static void 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);
  }
}
 
// This code is contributed by Aarti_Rathi
 
 

Javascript




<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 code
const 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>
 
 
Output
had No Repetition he            

Time complexity: O(N),because of for loop
Space Complexity: O(N),because of unordered_map/hashmap

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. 

Implementation:

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;
}
 
 

Java




// Java program for finding first repeated
// word in a string
import 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");
    }
}
 
 

Python3




class GFG:
    # returns first repeated word
    @staticmethod
    def findFirstRepeated(s):
        # break string into tokens
        # and then each string into set
        # if a word appeared before appears
        # again, return the word and break
        token = s.split(" ")
         
        # map for storing word and its count
        # in sentence
        setOfWords = {}
         
        # store all the words of string
        # and the count of word in map
        for i in range(len(token)):
            if token[i] in setOfWords:
                setOfWords[token[i]] += 1
            else:
                # insert new word to map
                setOfWords[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 array of strings in previous loop
        for i in range(len(token)):
            count = setOfWords[token[i]]
            if count > 1:
                return token[i]
         
        return "NoRepetition"
     
    # driver program
    @staticmethod
    def main(args):
        s = "Ravi had been saying that he had been there"
        firstWord = GFG.findFirstRepeated(s)
        if firstWord != "NoRepetition":
            print("First repeated word :: " + firstWord)
        else:
            print("No Repetition")
     
GFG.main([])
 
 
# This code is contributed by adityashatmfh
 
 

C#




// C# program for finding first repeated
// word in a string
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
 
class HelloWorld {
     
    // returns first repeated word
    public 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
        Dictionary<string, int> setOfWords = new Dictionary<string,int>();
 
        // store all the words of string
        // and the count of word in map
        for (int i=0; i < token.Length; i++)
        {
            if (setOfWords.ContainsKey(token[i]) == true)
            {
                setOfWords[token[i]] = setOfWords[token[i]] + 1;
            }
            else
            {
                // insert new word to map
                setOfWords.Add(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 array of strings in previous loop
        for (int i=0; i < token.Length; i++)
        {
            int count = setOfWords[token[i]];
            if (count > 1)
            {
                return token[i];
            }
        }
        return "NoRepetition";
    }   
 
    static void Main() {
        string s = "Ravi had been saying that he had been there";
        string firstWord = findFirstRepeated(s);
        if (firstWord != "NoRepetition")
            Console.WriteLine("First repeated word :: "  + firstWord);
        else
            Console.WriteLine("No Repitition");
    }
}
 
// The code is contributed by Nidhi goel.
 
 

Javascript




class GFG
{
    // returns first repeated word
    static findFirstRepeated(s)
    {
        // break string into tokens
        // and then each string into set
        // if a word appeared before appears
        // again, return the word and break
        var token = s.split(" ");
         
        // map for storing word and its count
        // in sentence
        var setOfWords = new Map();
        // store all the words of string
        // and the count of word in map
        for (let i=0; i < token.length; i++)
        {
            if (setOfWords.has(token[i]))
            {
                setOfWords.set(token[i],setOfWords.get(token[i]) + 1);
            }
            else
            {
                // insert new word to map
                setOfWords.set(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 array of strings in previous loop
        for (let i=0; i < token.length; i++)
        {
            var count = setOfWords.get(token[i]);
            if (count > 1)
            {
                return token[i];
            }
        }
        return "NoRepetition";
    }
    // driver program
    static main(args)
    {
        var s = "Ravi had been saying that he had been there";
        var firstWord = GFG.findFirstRepeated(s);
        if (firstWord !== "NoRepetition")
        {
            console.log("First repeated word :: " + firstWord);
        }
        else
        {
            console.log("No Repetitionn");
        }
    }
}
GFG.main([]);
 
// This code is contributed by mukulsomukesh
 
 
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

Implementation::

C++




#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
 
using namespace std;
 
string firstRepeatedWord(string sentence)
{
    // Splitting the string into words
    vector<string> words;
    size_t pos = 0;
    while ((pos = sentence.find(' ')) != string::npos)
    {
        string word = sentence.substr(0, pos);
        words.push_back(word);
        sentence.erase(0, pos + 1);
    }
    words.push_back(sentence); // Add the last word
 
    // Calculating the frequency of each word
    unordered_map<string, int> frequency;
    for (size_t i = 0; i < words.size(); i++)
    {
        string word = words[i];
        if (frequency.find(word) == frequency.end())
        {
            frequency[word] = 1;
        }
        else
        {
            frequency[word]++;
        }
    }
 
    // Traversing the list of words
    for (size_t i = 0; i < words.size(); i++)
    {
        string word = words[i];
        // Checking if the frequency is greater than 1
        if (frequency[word] > 1)
        {
            // Return the word
            return word;
        }
    }
 
    // If no repeated word is found
    return "No repeated word found";
}
 
int main()
{
    string sentence = "Vikram had been saying that he had been there";
    cout << firstRepeatedWord(sentence) << endl;
    return 0;
}
 
// This code is contributed by akshitaguprzj3
 
 

Java




import java.util.*; 
 
class GFG
{
  public static String firstRepeatedWord(String sentence)
  {
    // splitting the string
    String[] lis = sentence.split(" ");
 
    // Calculating frequency of every word
    Map<String, Integer> frequency = new HashMap<>();
    for (int i = 0; i < lis.length; i++)
    {
      String word = lis[i];
      if (!frequency.containsKey(word))
      {
        frequency.put(word, 1);
      }
      else
      {
        frequency.put(word, frequency.get(word) + 1);
      }
    }
 
    // Traversing the list of words
    for (int i = 0; i < lis.length; i++)
    {
      String word = lis[i];
      // checking if frequency is greater than 1
      if (frequency.get(word) > 1)
      {
        // return the word
        return word;
      }
    }
 
    // if no repeated word is found
    return "No repeated word found";
  }
 
  // Driver code
  public static void main(String[] args)
  {
    String sentence = "Vikram had been saying that he had been there";
    System.out.println(firstRepeatedWord(sentence));
  }
 
}
 
 

Python3




 
 

C#




using System;
using System.Collections.Generic;
 
class Program
{
    static string FirstRepeatedWord(string sentence)
    {
        // Splitting the string into words
        List<string> words = new List<string>();
        int pos;
        while ((pos = sentence.IndexOf(' ')) != -1)
        {
            string word = sentence.Substring(0, pos);
            words.Add(word);
            sentence = sentence.Remove(0, pos + 1);
        }
        words.Add(sentence); // Add the last word
 
        // Calculating the frequency of each word
        Dictionary<string, int> frequency = new Dictionary<string, int>();
        foreach (string word in words)
        {
            if (!frequency.ContainsKey(word))
            {
                frequency[word] = 1;
            }
            else
            {
                frequency[word]++;
            }
        }
 
        // Traversing the list of words
        foreach (string word in words)
        {
            // Checking if the frequency is greater than 1
            if (frequency[word] > 1)
            {
                // Return the word
                return word;
            }
        }
 
        // If no repeated word is found
        return "No repeated word found";
    }
 
    static void Main()
    {
        string sentence = "Vikram had been saying that he had been there";
        Console.WriteLine(FirstRepeatedWord(sentence));
    }
}
 
// This code is contributed by shivamgupta0987654321
 
 

Javascript




 
 
Output
had            

Another Approach: 

Instead of tracking the counts for a specific token(word), we can keep track of the first occurrence of the token(word) using an unordered map. This would not require any extra loop to traverse in a hashmap or a string to find the repeated string. Thus, it eventually transforms the time complexity from O(2*n) to O(n) while the space complexity remains the same.

Implementation:

C++




// CPP program to find first repeated word in a string.
#include <bits/stdc++.h>
using namespace std;
 
void solve(string s)
{
    int n = s.size(); // size of the string.
    unordered_map<string, int>
        mp; // To store first occurrence of a word.
    string ans = "", t = "";
    int min_idx = INT_MAX; // To get minimum occurrence in
                           // the given string.
 
    int i = 0,
        j = 0; // iterators. i -> initial index of a word
               //            j -> final index of a word.
 
    // loop to traverse in a string and to find out each
    // repeated word whose occurrence is minimum.
    while (j <= n) {
 
        // If found an entire word then check if it is
        // repeated or not using unordered_map.
        if (s[j] == ' ' || j == n) {
            if (mp[t] == 0) { // Store the first occurrence
                              // of a word.
                mp[t] = i + 1;
            }
            else { // If there is a Repetition then check
                   // for minimum occurrence of the word.
                if (min_idx > mp[t]) {
                    min_idx = mp[t];
                    ans = t;
                }
            }
 
            // Shift the pointers.
            t = "";
            i = j + 1;
            j = i;
        }
        else {
            t += s[j];
            j++;
        }
    }
 
    // If ans is of empty string then this signifies that
    // there is no Repetition.
    if (ans == "")
        cout << "No Repetition" << endl;
    else
        cout << ans << endl;
}
 
int main()
{
    string s1
        = "Ravi had been saying that he had been there";
    string s2 = "Ravi had been saying that";
    string s3 = "he had had he";
 
    solve(s1);
    solve(s2);
    solve(s3);
 
    return 0;
}
 
 

Java




// Java program to find first repeated word in a string.
 
import java.io.*;
import java.util.*;
 
import java.util.*;
 
public class Main {
     
    public static void solve(String s) {
        int n = s.length(); // size of the string.
        Map<String, Integer> mp = new HashMap<>(); // To store first occurrence of a word.
        String ans = "", t = "";
        int min_idx = Integer.MAX_VALUE; // To get minimum occurrence in the given string.
 
        int i = 0, j = 0; // iterators. i -> initial index of a word, j -> final index of a word.
 
        // loop to traverse in a string and to find out each
        // repeated word whose occurrence is minimum.
        while (j <= n) {
 
            // If found an entire word then check if it is
            // repeated or not using unordered_map.
            if (j == n || s.charAt(j) == ' ') {
                if (mp.getOrDefault(t, 0) == 0) { // Store the first occurrence of a word.
                    mp.put(t, i + 1);
                }
                else { // If there is a repetition then check for minimum occurrence of the word.
                    if (min_idx > mp.get(t)) {
                        min_idx = mp.get(t);
                        ans = t;
                    }
                }
 
                // Shift the pointers.
                t = "";
                i = j + 1;
                j = i;
            }
            else {
                t += s.charAt(j);
                j++;
            }
        }
 
        // If ans is an empty string then this signifies that
        // there is no Repetition.
        if (ans.equals(""))
            System.out.println("No Repetition");
        else
            System.out.println(ans);
    }
 
    public static void main(String[] args) {
        String s1 = "Ravi had been saying that he had been there";
        String s2 = "Ravi had been saying that";
        String s3 = "he had had he";
 
        solve(s1);
        solve(s2);
        solve(s3);
    }
}
 
// The code is contributed by Arushi Goel.
 
 

Python3




def find_first_repeated_word(s):
    n = len(s)  # Size of the string.
    mp = {}  # To store the first occurrence of a word.
    ans = ""
    t = ""
    min_idx = float('inf')  # To get the minimum occurrence in the given string.
 
    i = 0
    j = 0  # Iterators: i -> initial index of a word, j -> final index of a word.
 
    # Loop to traverse the string and find each repeated word whose occurrence is minimum.
    while j <= n:
        # If found an entire word, then check if it is repeated or not using a dictionary.
        if j == n or s[j] == ' ':
            if t not in mp:
                mp[t] = i + 1  # Store the first occurrence of a word.
            else:
                # If there is a repetition, then check for the minimum occurrence of the word.
                if min_idx > mp[t]:
                    min_idx = mp[t]
                    ans = t
 
            # Shift the pointers.
            t = ""
            i = j + 1
            j = i
        else:
            t += s[j]
            j += 1
 
    # If ans is an empty string, it signifies that there is no repetition.
    if ans == "":
        print("No Repetition")
    else:
        print(ans)
 
# Test cases
s1 = "Ravi had been saying that he had been there"
s2 = "Ravi had been saying that"
s3 = "he had had he"
 
find_first_repeated_word(s1)
find_first_repeated_word(s2)
find_first_repeated_word(s3)
 
# This code is contributed by shivamgupta310570
 
 

C#




using System;
using System.Collections.Generic;
 
public class MainClass
{
    public static void Solve(string s)
    {
        int n = s.Length; // size of the string.
        Dictionary<string, int> mp = new Dictionary<string, int>(); // To store first occurrence of a word.
        string ans = "", t = "";
        int min_idx = int.MaxValue; // To get minimum occurrence in the given string.
 
        int i = 0, j = 0; // iterators. i -> initial index of a word, j -> final index of a word.
 
        // loop to traverse in a string and to find out each
        // repeated word whose occurrence is minimum.
        while (j <= n)
        {
            // If found an entire word then check if it is
            // repeated or not using Dictionary.
            if (j == n || s[j] == ' ')
            {
                if (!mp.ContainsKey(t))
                {
                    mp[t] = i + 1; // Store the first occurrence of a word.
                }
                else
                {
                    // If there is a repetition then check for minimum occurrence of the word.
                    if (min_idx > mp[t])
                    {
                        min_idx = mp[t];
                        ans = t;
                    }
                }
 
                // Shift the pointers.
                t = "";
                i = j + 1;
                j = i;
            }
            else
            {
                t += s[j];
                j++;
            }
        }
 
        // If ans is an empty string then this signifies that
        // there is no Repetition.
        if (ans == "")
        {
            Console.WriteLine("No Repetition");
        }
        else
        {
            Console.WriteLine(ans);
        }
    }
 
    public static void Main(string[] args)
    {
        string s1 = "Ravi had been saying that he had been there";
        string s2 = "Ravi had been saying that";
        string s3 = "he had had he";
 
        Solve(s1);
        Solve(s2);
        Solve(s3);
    }
}
 
 

Javascript




 
 
Output
had No Repetition he            

This article is contributed by Aarti_Rathi and Mandeep Singh.



Next Article
Find the first maximum length even word from a string
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Strings
  • Amazon
  • cpp-stringstream
  • cpp-unordered_map
  • Goldman Sachs
Practice Tags :
  • Amazon
  • Goldman Sachs
  • Strings

Similar Reads

  • Find the first repeated word in a string in Python using Dictionary
    We are given a string that may contain repeated words and the task is to find the first word that appears more than once. For example, in the string "Learn code learn fast", the word "learn" is the first repeated word. Let's understand different approaches to solve this problem using a dictionary. U
    3 min read
  • Find repeated character present first in a string
    Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) Examples: Input : geeksforgeeks Output : g (mind that it will be g, not e.) Asked in: Goldman Sachs internship Simple Solution using O(N^2) complexity: The solution is to loop thro
    15 min read
  • Find the last non repeating character in string
    Given a string str, the task is to find the last non-repeating character in it. For example, if the input string is "GeeksForGeeks", then the output should be 'r' and if the input string is "GeeksQuiz" then the output should be 'z'. if there is no non-repeating character then print -1.Examples: Inpu
    5 min read
  • Find the first maximum length even word from a string
    Given a string of words separated by spaces. The task is to find the first maximum length even word from the string. Eg: “You are given an array of n numbers” The answer would be “an” and not “of” because “an” comes before “of”.Examples: Input: "this is a test string"Output: stringEven length words
    10 min read
  • Count words present in a string
    Given an array of words and a string, we need to count all words that are present in given string. Examples: Input : words[] = { "welcome", "to", "geeks", "portal"} str = "geeksforgeeks is a computer science portal for geeks." Output : 2 Two words "portal" and "geeks" is present in str. Input : word
    6 min read
  • Second most repeated word in a sequence
    Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. You may assume that no two words are the second most repeated, there will be always a single word. Examples: Input: ["aaa", "bbb", "ccc", "bbb", "aaa", "aaa"]Output: bbbExplanati
    7 min read
  • Remove the first and last character of each word in a string
    Given the string the task is to remove the first and last character of each word in a string.Examples: Input: Geeks for geeksOutput: eek o eek Input: Geeksforgeeks is bestOutput: eeksforgeek es Approach : Split the String based on the spaceRun a loop from the first letter to the last letter.Check if
    4 min read
  • Second most repeated word in a sequence in Python
    Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. (Considering no two words are the second most repeated, there will be always a single word). Examples: Input : {"aaa", "bbb", "ccc", "bbb", "aaa", "aaa"} Output : bbb Input : {"g
    4 min read
  • Find all words from String present after given N words
    Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third
    11 min read
  • Find a word with highest number of repeating characters
    Given a string which contains multiple words, our task is to find the word which has highest number of repeating characters. Examples: Input: str = "hello world programming"Output: "programming"Explanation: The word "programming" has the highest number of repeating characters, with 'r', 'g', and 'm'
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences