We can find duplicate characters in a string by using a for loop and a JavaScript object (dictionary) to store character counts.
Steps:
After the loop, print only those characters whose count is greater than 1 — these are the duplicates.
- Get the string input.
- Initialize an empty object to store character counts.
- Loop through each character in the string.
- For each character:
- If it already exists in the object, increment its count by 1.
- Otherwise, set its count to 1.
Example Code:
const str = “programming”;
const charCount = {};
let len = str.length;
for (let i = 0; i < len; i++) {
const char = str[i];
if (charCount[char]) {
charCount[char] += 1;
} else {
charCount[char] = 1;
}
}
// Display duplicate characters
console.log(“Duplicate characters:”);
for (let char in charCount) {
if (charCount[char] > 1) {
console.log(${char} - ${charCount[char]} times);
}
}