Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding duplicate "words" in a string - JavaScript
We need to write a JavaScript function that takes a string and returns only the words that appear more than once in the original string.
For example, if the input string is:
const str = "big black bug bit a big black dog on his big black nose";
Then the output should be:
"big black"
Solution Using indexOf() and lastIndexOf()
We can identify duplicates by comparing the first and last occurrence positions of each word:
const str = "big black bug bit a big black dog on his big black nose";
const findDuplicateWords = str => {
const strArr = str.split(" ");
const res = [];
for(let i = 0; i < strArr.length; i++){
if(strArr.indexOf(strArr[i]) !== strArr.lastIndexOf(strArr[i])){
if(!res.includes(strArr[i])){
res.push(strArr[i]);
}
}
}
return res.join(" ");
};
console.log(findDuplicateWords(str));
big black
How It Works
The algorithm works by:
- Splitting the string into an array of words using
split(" ") - For each word, comparing its first occurrence (
indexOf()) with its last occurrence (lastIndexOf()) - If these positions differ, the word appears multiple times
- Adding unique duplicates to the result array using
includes()check
Alternative Solution Using Map for Word Counting
const str = "big black bug bit a big black dog on his big black nose";
const findDuplicateWordsMap = str => {
const words = str.split(" ");
const wordCount = new Map();
// Count occurrences
words.forEach(word => {
wordCount.set(word, (wordCount.get(word) || 0) + 1);
});
// Filter words with count > 1
const duplicates = [];
wordCount.forEach((count, word) => {
if(count > 1) {
duplicates.push(word);
}
});
return duplicates.join(" ");
};
console.log(findDuplicateWordsMap(str));
big black
Comparison
| Method | Time Complexity | Readability |
|---|---|---|
| indexOf/lastIndexOf | O(n²) | Simple |
| Map counting | O(n) | More verbose |
Conclusion
Both methods effectively find duplicate words. The indexOf approach is simpler, while the Map method is more efficient for larger strings with many duplicates.
Advertisements
