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/
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++
#include<bits/stdc++.h>
using namespace std;
void solve(string s)
{
unordered_map<string,int> mp;
string t="",ans="";
for(int i=s.length()-1;i>=0;i--)
{
if(s[i]!=' ')
{
t+=s[i];
}
else
{
mp[t]++;
if(mp[t]>1)
ans=t;
t="";
}
}
mp[t]++;
if(mp[t]>1)
ans=t;
if(ans!="")
{
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 {
public static void solve(String s)
{
HashMap<String, Integer> mp
= new HashMap<String,
Integer>();
String t = "";
String ans = "";
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) != ' ') {
t += s.charAt(i);
}
else {
if (!mp.containsKey(t)) {
mp.put(t, 1);
}
else {
mp.put(t, mp.get(t) + 1);
}
if (mp.get(t) > 1) {
ans = t;
}
t = "";
}
}
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("")) {
StringBuilder input1 = new StringBuilder();
input1.append(ans);
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);
}
}
|
Python3
def solve(s):
mp = {}
t = ""
ans = ""
for i in range(len(s) - 1,-1,-1):
if(s[i] != ' '):
t += s[i]
else:
if(t in mp):
ans = t
else:
mp[t] = 1
t = ""
if(t in mp):
ans=t
if(ans!=""):
ans = ans[::-1]
print(ans)
else:
print("No Repetition")
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)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void solve(string s)
{
Dictionary<string, int> mp = new Dictionary<
string, int>();
string t = "";
string ans = "";
for (int i = s.Length - 1; i >= 0; i--) {
if (s[i] != ' ') {
t += s[i];
}
else {
if (mp.ContainsKey(t)) {
mp[t] += 1;
}
else {
mp.Add(t, 1);
}
if (mp[t] > 1) {
ans = t;
}
t = "";
}
}
if (mp.ContainsKey(t)) {
mp[t] += 1;
}
else {
mp.Add(t, 1);
}
if (mp[t] > 1) {
ans = t;
}
if (ans != "") {
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);
}
}
|
Javascript
<script>
function solve(s)
{
let mp = new Map();
let t = "";
let ans = "";
for(let i = s.length - 1; i >= 0; i--)
{
if(s[i] != ' ')
{
t += s[i];
}
else
{
if(mp.has(t))
ans = t;
else mp.set(t, 1)
t = "";
}
}
if(mp.has(t)) ans=t;
if(ans!="")
{
ans = [...ans].reverse().join("");
document.write(ans);
}
else
document.write("No Repetition");
}
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);
</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
#include <bits/stdc++.h>
using namespace std;
string findFirstRepeated(string s)
{
istringstream iss(s);
string token;
unordered_map<string, int> setOfWords;
while (getline(iss, token, ' ')) {
if (setOfWords.find(token) != setOfWords.end())
setOfWords[token] += 1;
else
setOfWords.insert(make_pair(token, 1));
}
istringstream iss2(s);
while (getline(iss2, token, ' ')) {
int count = setOfWords[token];
if (count > 1) {
return token;
}
}
return "NoRepetition";
}
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
import java.util.*;
class GFG{
static String findFirstRepeated(String s)
{
String token[] = s.split(" ");
HashMap<String, Integer> setOfWords = new HashMap<String, Integer>();
for (int i=0; i<token.length; i++) {
if (setOfWords.containsKey(token[i]))
setOfWords.put(token[i], setOfWords.get(token[i]) + 1);
else
setOfWords.put(token[i], 1);
}
for (int i=0; i<token.length; i++) {
int count = setOfWords.get(token[i]);
if (count > 1) {
return token[i];
}
}
return "NoRepetition";
}
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:
@staticmethod
def findFirstRepeated(s):
token = s.split(" ")
setOfWords = {}
for i in range(len(token)):
if token[i] in setOfWords:
setOfWords[token[i]] += 1
else:
setOfWords[token[i]] = 1
for i in range(len(token)):
count = setOfWords[token[i]]
if count > 1:
return token[i]
return "NoRepetition"
@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([])
|
C#
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
class HelloWorld {
public static string findFirstRepeated(string s)
{
string[] token = s.Split(" ");
Dictionary<string, int> setOfWords = new Dictionary<string,int>();
for (int i=0; i < token.Length; i++)
{
if (setOfWords.ContainsKey(token[i]) == true)
{
setOfWords[token[i]] = setOfWords[token[i]] + 1;
}
else
{
setOfWords.Add(token[i], 1);
}
}
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");
}
}
|
Javascript
class GFG
{
static findFirstRepeated(s)
{
var token = s.split(" ");
var setOfWords = new Map();
for (let i=0; i < token.length; i++)
{
if (setOfWords.has(token[i]))
{
setOfWords.set(token[i],setOfWords.get(token[i]) + 1);
}
else
{
setOfWords.set(token[i],1);
}
}
for (let i=0; i < token.length; i++)
{
var count = setOfWords.get(token[i]);
if (count > 1)
{
return token[i];
}
}
return "NoRepetition";
}
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([]);
|
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)
{
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);
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]++;
}
}
for (size_t i = 0; i < words.size(); i++)
{
string word = words[i];
if (frequency[word] > 1)
{
return word;
}
}
return "No repeated word found";
}
int main()
{
string sentence = "Vikram had been saying that he had been there";
cout << firstRepeatedWord(sentence) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static String firstRepeatedWord(String sentence)
{
String[] lis = sentence.split(" ");
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);
}
}
for (int i = 0; i < lis.length; i++)
{
String word = lis[i];
if (frequency.get(word) > 1)
{
return word;
}
}
return "No repeated word found";
}
public static void main(String[] args)
{
String sentence = "Vikram had been saying that he had been there";
System.out.println(firstRepeatedWord(sentence));
}
}
|
Python3
from collections import Counter
def firstRepeatedWord(sentence):
lis = list(sentence.split(" "))
frequency = Counter(lis)
for i in lis:
if(frequency[i] > 1):
return i
sentence = "Vikram had been saying that he had been there"
print(firstRepeatedWord(sentence))
|
C#
using System;
using System.Collections.Generic;
class Program
{
static string FirstRepeatedWord(string sentence)
{
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);
Dictionary<string, int> frequency = new Dictionary<string, int>();
foreach (string word in words)
{
if (!frequency.ContainsKey(word))
{
frequency[word] = 1;
}
else
{
frequency[word]++;
}
}
foreach (string word in words)
{
if (frequency[word] > 1)
{
return word;
}
}
return "No repeated word found";
}
static void Main()
{
string sentence = "Vikram had been saying that he had been there";
Console.WriteLine(FirstRepeatedWord(sentence));
}
}
|
Javascript
function firstRepeatedWord(sentence) {
let lis = sentence.split(" ");
let frequency = {};
for (let i = 0; i < lis.length; i++) {
let word = lis[i];
if (!frequency[word]) {
frequency[word] = 1;
} else {
frequency[word]++;
}
}
for (let i = 0; i < lis.length; i++) {
let word = lis[i];
if (frequency[word] > 1) {
return word;
}
}
}
let sentence = "Vikram had been saying that he had been there";
console.log(firstRepeatedWord(sentence));
|
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++
#include <bits/stdc++.h>
using namespace std;
void solve(string s)
{
int n = s.size();
unordered_map<string, int>
mp;
string ans = "", t = "";
int min_idx = INT_MAX;
int i = 0,
j = 0;
while (j <= n) {
if (s[j] == ' ' || j == n) {
if (mp[t] == 0) {
mp[t] = i + 1;
}
else {
if (min_idx > mp[t]) {
min_idx = mp[t];
ans = t;
}
}
t = "";
i = j + 1;
j = i;
}
else {
t += s[j];
j++;
}
}
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
import java.io.*;
import java.util.*;
import java.util.*;
public class Main {
public static void solve(String s) {
int n = s.length();
Map<String, Integer> mp = new HashMap<>();
String ans = "", t = "";
int min_idx = Integer.MAX_VALUE;
int i = 0, j = 0;
while (j <= n) {
if (j == n || s.charAt(j) == ' ') {
if (mp.getOrDefault(t, 0) == 0) {
mp.put(t, i + 1);
}
else {
if (min_idx > mp.get(t)) {
min_idx = mp.get(t);
ans = t;
}
}
t = "";
i = j + 1;
j = i;
}
else {
t += s.charAt(j);
j++;
}
}
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);
}
}
|
Python3
def find_first_repeated_word(s):
n = len(s)
mp = {}
ans = ""
t = ""
min_idx = float('inf')
i = 0
j = 0
while j <= n:
if j == n or s[j] == ' ':
if t not in mp:
mp[t] = i + 1
else:
if min_idx > mp[t]:
min_idx = mp[t]
ans = t
t = ""
i = j + 1
j = i
else:
t += s[j]
j += 1
if ans == "":
print("No Repetition")
else:
print(ans)
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)
|
C#
using System;
using System.Collections.Generic;
public class MainClass
{
public static void Solve(string s)
{
int n = s.Length;
Dictionary<string, int> mp = new Dictionary<string, int>();
string ans = "", t = "";
int min_idx = int.MaxValue;
int i = 0, j = 0;
while (j <= n)
{
if (j == n || s[j] == ' ')
{
if (!mp.ContainsKey(t))
{
mp[t] = i + 1;
}
else
{
if (min_idx > mp[t])
{
min_idx = mp[t];
ans = t;
}
}
t = "";
i = j + 1;
j = i;
}
else
{
t += s[j];
j++;
}
}
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
function solve(s)
{
const n = s.length;
const mp = new Map();
let ans = "", t = "";
let min_idx = Number.MAX_SAFE_INTEGER;
let i = 0, j = 0;
while (j <= n)
{
if (s[j] === ' ' || j === n) {
if (!mp.has(t)) {
mp.set(t, i + 1);
}
else
{
if (min_idx > mp.get(t))
{
min_idx = mp.get(t);
ans = t;
}
}
t = "";
i = j + 1;
j = i;
} else {
t += s[j];
j++;
}
}
if (ans === "")
console.log("No Repetition");
else
console.log(ans);
}
const s1 = "Ravi had been saying that he had been there";
const s2 = "Ravi had been saying that";
const s3 = "he had had he";
solve(s1);
solve(s2);
solve(s3);
|
Output
had
No Repetition
he
Optimized Approach:
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”.
Implementation:
C++
#include <iostream>
#include <map>
#include <string>
#include <sstream>
using namespace std;
string first_repeating_word(string s) {
map<string, int> word_count;
stringstream ss(s);
string word;
while (ss >> word) {
if (word_count.find(word) != word_count.end()) {
word_count[word]++;
}
else {
word_count[word] = 1;
}
if (word_count[word] > 1) {
return word;
}
}
return "No word is being repeated";
}
int main() {
string s = "Ravi had been saying that he had been there";
cout << first_repeating_word(s);
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static String firstRepeatingWord(String s) {
Map<String, Integer> wordCount = new HashMap<>();
String[] words = s.split(" ");
for (String word : words) {
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
if (wordCount.get(word) > 1) {
return word;
}
}
return "No word is being repeated";
}
public static void main(String[] args) {
String s = "Ravi had been saying that he had been there";
System.out.println(firstRepeatingWord(s));
}
}
|
Python3
from collections import defaultdict
def first_repeating_word(s):
word_count = defaultdict(lambda: 0)
for i in s.split():
word_count[i] += 1
if word_count[i] > 1:
return i
return 'No word is being repeated'
if __name__ == '__main__':
s = "Ravi had been saying that he had been there"
print(first_repeating_word(s))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static string FirstRepeatingWord(string s)
{
Dictionary<string, int> wordCount = new Dictionary<string, int>();
string[] words = s.Split(new char[] { ' ', '.', ',', '!', '?' },
StringSplitOptions.RemoveEmptyEntries);
foreach (string word in words)
{
string lowercaseWord = word.ToLower();
if (wordCount.ContainsKey(lowercaseWord))
{
wordCount[lowercaseWord]++;
}
else
{
wordCount[lowercaseWord] = 1;
}
if (wordCount[lowercaseWord] > 1)
{
return word;
}
}
return "No word is being repeated";
}
static void Main(string[] args)
{
string s = "Ravi had been saying that he had been there";
Console.WriteLine(FirstRepeatingWord(s));
}
}
|
Javascript
<script>
function first_repeating_word(s){
let word_count = new Map()
for(let i of s.split(' ')){
if(word_count.has(i)){
word_count.set(i,word_count.get(i) + 1);
}
else word_count.set(i,1);
if(word_count.get(i) > 1)
return i
}
return 'No word is being repeated'
}
let s = "Ravi had been saying that he had been there"
document.write(first_repeating_word(s))
</script>
|
Time complexity: O(M)
Space Complexity: O(M)
Optimized Approach 2:
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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
string findFirstRepeated(string s)
{
istringstream iss(s);
string token;
set<string> setOfWords;
while (getline(iss, token, ' ')) {
if (setOfWords.find(token) != setOfWords.end()) {
return token;
}
setOfWords.insert(token);
}
return "NoRepetition";
}
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
import java.util.*;
public class GFG{
static String findFirstRepeated(String s)
{
String token[] = s.split(" ");
HashSet<String> set = new HashSet<String>();
for(int i=0; i<token.length; i++){
if(set.contains(token[i])){
return token[i];
}
set.add(token[i]);
}
return "NoRepetition";
}
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
def findFirstRepeated(s):
tokens = s.split()
setOfWords = set()
for token in tokens:
if token in setOfWords:
return token
setOfWords.add(token)
return "NoRepetition"
if __name__ == "__main__":
s = "Ravi had been saying that he had been there"
firstWord = findFirstRepeated(s)
if firstWord != "NoRepetition":
print("First repeated word ::", firstWord)
else:
print("No Repetition")
|
C#
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static string FindFirstRepeated(string s)
{
var tokens = s.Split(' ');
var setOfWords = new HashSet<string>();
foreach (var token in tokens)
{
if (setOfWords.Contains(token))
{
return token;
}
setOfWords.Add(token);
}
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 Repetition");
}
}
}
|
Javascript
class GFG
{
static findFirstRepeated(s)
{
var token = s.split(" ");
var set = new Set();
for (let i=0; i < token.length; i++)
{
if (set.has(token[i]))
{
return token[i];
}
set.add(token[i]);
}
return "NoRepetition";
}
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([]);
|
Output
First repeated word :: had
This article is contributed by Aarti_Rathi and 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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
24 Nov, 2023
Like Article
Save Article