Finding the first non-repeating character javascript

Viewed 529

I tried to solve the problem below on a site, but they keep saying that something is not right when I reach certain tests.

Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return "_".

I tried this

function firstNotRepeatingCharacter(s) {
    let strArr = s.replace(" ", "").split(""),
        newArr = [];
    for (let i = 0; i < strArr.length; i++) {
        newArr = strArr.filter(lol => lol === strArr[i]);
        if (newArr.length === 1) {
            return newArr[0];  
        };
    };
    return "_";
};
console.log(firstNotRepeatingCharacter("abacabad"));

It works for 16 out of 19 tests. why not all

2 Answers

Thanks all! I've found an answer.

function firstNotRepeatingCharacter(s) {
    let strArr = s.replace(" ", "").split("");
    for (let str of strArr) 
        if(strArr.indexOf(str) == strArr.lastIndexOf(str))
            return str;
        
    return "_";
};
console.log(firstNotRepeatingCharacter("abacabad"));

another approach with a better time complexity:

function firstNotRepeatingCharacter(s) {
  const seenBefore = new Set();
  let result = "_";
  for (let i = s.length; i--;) {
    const char = s.charAt(i);
    if (seenBefore.has(char)) continue;
    seenBefore.add(char);
    result = char;
  }
  return result;
}

console.log(firstNotRepeatingCharacter("abacabad"));

Related