How to use Nested for loop In Javascript

  • In this approach we splits the input sentence into an array of words and then uses nested for loop to compare each word with every other word that comes after it.
  • If a match is found we will return that word as the first repeated word.

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

JavaScript
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)

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:

Table of Content

  • Using Set
  • Using indexOf method
  • Using Nested for loop
  • Using a Map
  • Using an Object

Similar Reads

Using Set

In this approach, we are using a Set data structure to track unique words encountered during iteration over the input string. If a word is already in the set, itā€™s identified as the first repeated word; otherwise, the result remains ā€œNo Repetitionā€....

Using indexOf method

In this approach, we are using the indexOf method to check if the current word appears again later in the array of words. If it does, the word is identified as the first repeated word; otherwise, the result remains ā€œNo Repetitionā€....

Using Nested for loop

In this approach we splits the input sentence into an array of words and then uses nested for loop to compare each word with every other word that comes after it.If a match is found we will return that word as the first repeated word....

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()....

Using an Object

In this approach, we use an object to track the frequency of each word. We iterate over each word in the array of words. For each word, we check if the object already has the word as a key. If the word is found, we return it as the first repeated word. Otherwise, we add it to the object with a count....

Contact Us