JavaScript Program to Check for Repeated Characters in a String

In this article, we are going to see various methods with which you can detect repeated characters in a string. Checking for repeated characters in a string involves examining the string’s content to identify if any character occurs more than once. This helps detect duplications or repetitions within the text.

Input: Str = “w3wiki”
Output:
e, count = 4
g, count = 2
k, count = 2
s, count = 2
Explanation: e,g,k,and s are characters which are occured in string in more than one times.

There are several methods that can be used to Check for repeated characters in a string JavaScript.

Table of Content

  • Using sort() method with for…of loop
  • Using a Set in JavaScript
  • Without using Extra Data Structure
  • Using a Map
  • Using Object as a Frequency Counter:

We will explore all the above methods along with their basic implementation with the help of examples.

Using sort() method with for…of loop

In this approach,we utilize the sort() method to alphabetically sort the characters of our inputStr. Then, we employ a for…of loop to iterate through the sorted string, identifying and gathering duplicate characters while ensuring they are not duplicated within an array.

Syntax:

array.sort()

Example: In this example we are using the above-explained approach.

Javascript
const inputStr = "w3wiki";
const sortedStr = inputStr.split('').sort().join('');

let duplicates = [];
let prevChar = sortedStr[0];

for (const char of sortedStr.slice(1)) {
    if (char === prevChar
        && !duplicates.includes(char)) {
        duplicates.push(char);
    }
    prevChar = char;
}

if (duplicates.length > 0) {
    console.log(`The duplicate characters : ${duplicates.join(', ')}`);
} else {
    console.log(`The string "${inputStr}" has no duplicate characters.`);
};

Output
The duplicate characters : G, e, k, s

Using a Set in JavaScript

In this approach we use a Set to efficiently find and store duplicate characters in a given string. It iterates through the string, adding each character to the Set if it’s not already present, and adds it to the ‘duplicates’ array if it’s encountered again.

Syntax:

new Set([it]);

Example: In this example we are using above explained apporach.

Javascript
const str = "w3wiki";
const cSet = new Set();
const duplicates = [];

for (let i = 0; i < str.length; i++) {
    const char = str[i];

    if (cSet.has(char)) {
        if (!duplicates.includes(char)) {
            duplicates.push(char);
        }
    } else {
        cSet.add(char);
    }
}

if (duplicates.length > 0) {
    console.log(
`The String ${str} has duplicate characters: ${duplicates.join(", ")}`);
} else {
    console.log(`The String ${str} has all unique characters`);
};

Output
The String w3wiki has duplicate characters: e, G, k, s

Without using Extra Data Structure

In this approach, we are using bit manipulation to find the check for repeated characters in a string. we use a bit vector (checker) to efficiently find and collect duplicate characters in a string. It iterates through the string, tracking character occurrences with bitwise operations and stores duplicates in an array

Syntax:

if ((checker & (1 << bitAtIndex)) > 0) {
if (!duplicates.includes(str[i])) {
duplicates.push(str[i]);
}
} else {
checker |= (1 << bitAtIndex);
};

Example: In this example we are using above-explained apporach.

Javascript
function findDuplicateChar(str) {
    let checker = 0;
    const duplicates = [];

    for (let i = 0; i < str.length; i++) {
        const bitAtIndex =
            str.charCodeAt(i) - 'a'.charCodeAt(0);

        if ((checker & (1 << bitAtIndex)) > 0) {
            if (!duplicates.includes(str[i])) {
                duplicates.push(str[i]);
            }
        } else {
            checker |= (1 << bitAtIndex);
        }
    }

    return duplicates;
}

const str = "w3wiki";
const duplicateCharacters = findDuplicateChar(str);

if (duplicateCharacters.length > 0) {
    console.log(
        "The String ${str} has duplicate characters:",
            duplicateCharacters.join(", "));
} else {
    console.log(
`The String ${str} has all unique characters`);
};

Output
The String ${str} has duplicate characters: e, G, k, s

Using a Map

Using a Map, iterate through the string, storing each character as a key and its count as the value. If a character is already in the map, return true; otherwise, continue. If no characters repeat, return false.

Example: In this example we counts duplicate characters in a string using a Map, then prints them or a message if none exist.

JavaScript
const inputStr = "w3wiki";
const charCount = new Map();

// Count occurrences of each character
for (const char of inputStr) {
    if (charCount.has(char)) {
        charCount.set(char, charCount.get(char) + 1);
    } else {
        charCount.set(char, 1);
    }
}

const duplicates = [];

// Find characters with count > 1
for (const [char, count] of charCount) {
    if (count > 1) {
        duplicates.push(char);
    }
}

// Print duplicates or no duplicates message
if (duplicates.length > 0) {
    console.log(`The duplicate characters: ${duplicates.join(', ')}`);
} else {
    console.log(`The string "${inputStr}" has no duplicate characters.`);
}

Output
The duplicate characters: G, e, k, s

Using Object as a Frequency Counter:

In this approach, we use an object as a frequency counter to track the occurrence of each character in the string. We iterate through the string, incrementing the count of each character in the object. After iterating through the string, we check the object to identify which characters have a count greater than 1, indicating that they are repeated.

JavaScript
const str = "w3wiki";
const charCount = {};

// Count occurrences of each character
for (const char of str) {
    charCount[char] = (charCount[char] || 0) + 1;
}

const duplicates = [];

// Find characters with count > 1
for (const char in charCount) {
    if (charCount[char] > 1) {
        duplicates.push(char);
    }
}

// Print duplicates or no duplicates message
if (duplicates.length > 0) {
    console.log(`The duplicate characters: ${duplicates.join(', ')}`);
} else {
    console.log(`The string "${str}" has no duplicate characters.`);
}

Output
The duplicate characters: G, e, k, s




Contact Us