Open In App

JavaScript Program to Find the First Repeated Word in String

Given a string, our task is to 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

Below are the approaches to Finding the first repeated word in a string:

Using Set

Example: The below example uses Set to Find the first repeated word in a string.

let str = "GFG had been saying that he had been there";
let words = str.split(" ");
let wSet = new Set();
let res = "No Repetition";
for (let word of words) {
    if (wSet.has(word)) {
        res = word;
        break;
    } else {
        wSet.add(word);
    }
}
console.log(res);

Output:

had

Time Complexity: O(n), where n is the number of words in the input.

Space Complexity: O(n)

Using indexOf method

Example: The below example uses indexOf to Find the first repeated word in a string.

let str = "Ravi had been saying that he been there";
let words = str.split(" ");
let res = "No Repetition";
for (let i = 0; i < words.length; i++) {
    if (words.indexOf(words[i]) !== i) {
        res = words[i];
        break;
    }
}
console.log(res);

Output:

been

Time Complexity: O(n^2), where n is the number of words in the input.

Space Complexity: O(1)

Using Nested for loop

Example: The below example uses nested for loop to Find the first repeated word in a string.

function findFirstRepeatedWord(sentence) {
    const words = sentence.split(' ');

    for (let i = 0; i < words.length; i++) {
        for (let j = i + 1; j < words.length; j++) {
            if (words[i] === words[j]) {
                return words[i];
            }
        }
    }

    return null;
}

const sentence = "Ravi had been saying that he had been there";
const repeatedWord = findFirstRepeatedWord(sentence);
console.log(repeatedWord);

Output
had

Time Complexity: O(n^2), where n is the number of words in the input.

Space Complexity: O(1)

Using a Map

In this approach we use map to track the frequency of each word. we iterate over each word in the array of words. For each word, it checks if map already has the word using Map.has(). if the word is found we will return it, otherwise we add it to the map sing Map.set().

Example: The below example uses map to find the first Repeated Word in String.

function findFirstRepeatedWord(str) {
    const words = str.toLowerCase().split(' ');
    const wordMap = new Map();
    
    for (let word of words) {
        if (wordMap.has(word)) {
            return word;
        } else {
            wordMap.set(word, 1);
        }
    }
    
    return null;
}

const str = "GFG had been saying that he had been there";
const repeatedWord = findFirstRepeatedWord(str);
console.log(repeatedWord);

Output
had


Article Tags :