Santhiya Santhiya - 5 months ago 8
Javascript Question

Checking if the characters in a string are all unique

I am trying to solve this problem using JS by just using an array.

var str="abcdefgh";
for (i=0;i<255;i++){
arr[i]=false;
}
function check(){
for (i=0;i<str.length;i++){
if (arr[str.charCodeAt(i)]==true){
return false;
}
arr[str.charCodeAt(i)]=true;
}
return true;
}


I am initializing an array of fixed size 256 to have the boolean value
false
.
Then i am setting the value for the corresponding ASCII index to true for characters in the string. And if i find the same character again, i am returning
false
.

While running the program, i am getting false returned even if the string doesn't have any duplicate characters.

Answer

Use object for faster result

function is_unique(str) {
  var obj = {};
  for(var z=0;z<str.length;++z) {
    var ch = str[z];
    if(obj[ch]) return false; else obj[ch] = true;
  }
  return true;
}
// test:
console.log(is_unique("abcdefgh")); // true
console.log(is_unique("aa")); // false