2

I'm wondering what is the best way to determine if a string contains repeated characters even when they are not adjacent together? I have tried changing the string into an array and then using nested for loops to compare each item in the array with the other one but for some reason it doesn't work.

function hasRpeatedCharacters(str) {

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

    }

    for (let j = 0; j < array.length; j++) {

        for (let k = j + 1; k < array.length; k++) {

            if (array[j] != array[k]) {
                return true;
            } else {
                return false;
            }
        }

    }

}

hasRepeatedCharacters("abadan");
Mo Pishdar
  • 113
  • 1
  • 13

1 Answers1

3

Create a Set from the string, and check if the Set's size is less than the string's length. A Set can only hold unique values, so if there are repeated characters the Set's size would be less than the string's length.

const hasRepeatedCharacters = str => new Set(str).size < str.length;

console.log(hasRepeatedCharacters("abadan"));
console.log(hasRepeatedCharacters("abc"));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209