Untitled
function findDuplicates(chars) { let charCount = {}; // Object to store character counts let duplicates = new Set(); // Set to store characters appearing at least twice // Iterate through the array of characters for (let char of chars) { if (charCount[char]) { // If character is already counted, add it to duplicates set duplicates.add(char); } else { // Otherwise, mark it as seen for the first time charCount[char] = 1; } } // Convert the set to an array and return it return Array.from(duplicates); } // Example usage console.log(findDuplicates(['c', 'a', 'i', 'o', 'p', 'a'])); // Output: ['a']
Leave a Comment