Santhiya
Santhiya

Reputation: 119

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.

Upvotes: 9

Views: 12617

Answers (12)

Arvind kumar
Arvind kumar

Reputation: 87

Algorithm

  1. First string is "stack"

  2. String covert to CharArray

  3. Use iteration in array ['s','t','a','c','k']

  4. return beginElement !== nextElement

Implement code

function uniqueChars(string){
var charArray = Array.from(string) //convert charArray
  for(var i=0;i<charArray.length;i++){
    return charArray[i] !== charArray[i+1]
  }
}
var string = "stack"
console.log(uniqueChars(string))

Time complexity

O(nlogn)

Upvotes: 0

faezeh foroohar
faezeh foroohar

Reputation: 65

We can use split method of string:

const checkString = (str) => {
let isUniq = true;

for (let i = 0; i < str.length; i++) {
  if (str.split(str[i]).length > 2) {
    isUniq = false;
    break;
  }
}
return isUniq;
};
console.log(checkString("abcdefgh")); //true
console.log(checkString("aa")); //false

Upvotes: 0

kailash N
kailash N

Reputation: 11

To make efficient one, you can use simple hash map

let isUnique = (s) => {
    let ar = [...s];
    let check = {};
    for (let a of ar) {
        if (!check[a]) {
            check[a] = 1;
        } else {
            return false
        }
    }
    return true;
}
alert("isUnique : "+isUnique("kailu"));

Time complexity & Space complexity

using ES6

let isUnique = (s)=>{
   return new Set([...s]).size == s.length;
}
console.log("using ES6 : ",isUnique("kailu"));

Upvotes: 0

Penny Liu
Penny Liu

Reputation: 17398

Algo

  1. Counting frequency of alphabets. e.g. 'Mozilla' will returns Object{ M: 1, o: 1, z: 1, i: 1, l: 2, a: 1 }. Note that, the bitwise NOT operator (~) on -~undefined is 1, -~1 is 2, -~2 is 3 etc.
  2. Return true when all occurrences appear only once.

Implement code

var isUnique = (str) => {
  const hash = {};
  for (const key of str) {
    hash[key] = -~hash[key];
  }
  return Object.values(hash).every((t) => t === 1);
};

console.log(isUnique('Mozilla'));
console.log(isUnique('Firefox'));


Another alternative could be:

var isUnique = (str) => {
  const hash = {};
  for (const i in str) {
    if (hash[str[i]]) return false;
    hash[str[i]] = true;
  }
  return true;
};

console.log(isUnique('Mozilla'));
console.log(isUnique('Firefox'));

Upvotes: 0

Kokizzu
Kokizzu

Reputation: 26818

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;
    obj[ch] = true;
  }
  return true;
}

console.log(is_unique("abcdefgh")); // true
console.log(is_unique("aa")); // false

Upvotes: 11

Mayank_VK
Mayank_VK

Reputation: 17

We can also try using indexOf and lastIndexOf method:

function stringIsUnique(input) {
  for (i = 0; i < input.length; i++) {
    if (input.indexOf(input[i]) !== input.lastIndexOf(input[i])) {
      return false;
    }
  }
  return true;
}

Upvotes: 0

iamsourabhh
iamsourabhh

Reputation: 21

Use an object as a mapper

function uniqueCharacterString(inputString) {
  const characterMap = {};

  let areCharactersUnique = true;

  inputString.trim().split("").map((ch)=>{
    if(characterMap[ch]===undefined) {
      characterMap[ch] = 1;
    } else {
      areCharactersUnique = false;
    }
  })
  return areCharactersUnique;
}

Upvotes: 0

ASHISH R
ASHISH R

Reputation: 4189

// no additional Data structure is required. we can use naive solution
// Time Complexity:O(n^2)
function isUnique(str) {
  for (let i = 0; i < str.length; i++) {
    for (let j = 1 + i; j < str.length; j++) {
      if (str[i] === str[j]) {
        return false;
      }
    }
  }
  return true;
}

// if you can use additional Data structure 
// Time Complexity:O(n)
function isUniqueSecondMethos(str) {
  let dup_str = new Set();
  for (let i = 0; i < str.length; i++) {
    if (dup_str.has(str[i])) {
      return false;
    }
    dup_str.add(str[i]);
  }
  return true;
}
console.log(isUniqueSecondMethos('hello'));

Upvotes: 0

Pranava S Balugari
Pranava S Balugari

Reputation: 11

Time complexity = O(n) Space complexity = O(n)

const isUnique = (str) => {
      let charCount = {};
      for(let i = 0; i < str.length; i++) {
        if(charCount[str[i]]){
          return false;
        }

        charCount[str[i]] = true;
      }

      return true;
    }


    const isUniqueCheekyVersion = (str) => {
      return new Set(str).size === str.length;
    }

Solution 3: Transform string to chars array, sort them and then loop through them to check the adjacent elements, if there is a match return false else true

Solution 4: It's similar to Solution 1 except that we use a Set data structure which is introduced in recent versions of javascript

Upvotes: 0

le_m
le_m

Reputation: 20228

Fill a Set with all characters and compare its size to the string's length:

function isUnique(str) {
  return new Set(str).size == str.length;
}

console.log(isUnique('abc'));    // true
console.log(isUnique('abcabc')); // false

Upvotes: 25

Shreejibawa
Shreejibawa

Reputation: 1868

use .match() function for each of the character. calculate occurrences using length. Guess thats it.

(str.match(/yourChar/g) || []).length

Upvotes: 1

Ajay
Ajay

Reputation: 91

You are using arr[str.charCodeAt(i)] which is wrong. It should be arr[str[i].charCodeAt(0)]

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

Upvotes: 0

Related Questions