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