একটি স্ট্রিংয়ে একাধিকবার আবির্ভূত শব্দগুলো বের করে একটি স্ট্রিং আকারে রিটার্ন করা।
উদাহরণ
"big black bug bit a big black dog on his big black nose" // ডুপ্লিকেট শব্দ: "big" (৩ বার), "black" (৩ বার) // ফলাফল: "big black"
সমাধান
const findDuplicateWords = (str) => {
const words = str.split(' ');
const seen = new Set();
const duplicates = new Set();
for (const word of words) {
if (seen.has(word)) {
duplicates.add(word);
} else {
seen.add(word);
}
}
return [...duplicates].join(' ');
};
// ফাংশনাল পদ্ধতি
const findDuplicateWordsFP = (str) => {
return str
.split(' ')
.filter((word, index, arr) => arr.indexOf(word) !== index)
.filter((word, index, arr) => arr.indexOf(word) === index)
.join(' ');
};
// টেস্ট
const str = "big black bug bit a big black dog on his big black nose";
console.log(findDuplicateWords(str)); // "big black"
console.log(findDuplicateWordsFP(str)); // "big black"
// কেস-ইনসেনসিটিভ
const findDuplicateWordsCI = (str) => {
const words = str.toLowerCase().split(' ');
const seen = new Set();
const duplicates = new Set();
for (const word of words) {
if (seen.has(word)) duplicates.add(word);
else seen.add(word);
}
return [...duplicates].join(' ');
};
পারফরম্যান্স তুলনা
| পদ্ধতি | সময় জটিলতা | স্থান জটিলতা |
|---|---|---|
| Set (দুটি) | O(n) | O(n) |
| filter + indexOf | O(n²) | O(n) |
| Map (ফ্রিকোয়েন্সি) | O(n) | O(n) |
উৎপাদন
big black