-1

I was looking through leetcode and found problem with a solution I couldn't quite reason through.

Description of problem: "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 '_'."

Solution:

/*test word*/ var word = "abcdefghijklmnopqrstuvwxyziflskecznslkjfabe";
/*Test #2 var word = "abacabad"; */
firstNotRepeatingChar = s => {
    var arr = s.split("");
    for(var i = 0; i < arr.length; i++){
        if(arr.indexOf(arr[i]) == arr.lastIndexOf(arr[i]))
            return arr[i];
    }
    return "_"
};

firstNotRepeatingChar(word);

I was wondering if i could have someone explain how this works and why it comes out the solution of "d". Test # 2 should print "c", which it does, but I don't fully understand why.

Many thanks!

2 Answers 2

4

It splits s into an array of individual characters then loops through the resulting array. For each element (character) it checks if the first and last instance of that character in the array are in the same place. If so, then it must be the only instance of that character in the array.

And by the way the solution can be simplified as follows:

const firstNotRepeatingChar = s => {
  for (let c of s) {
    if (s.indexOf(c) === s.lastIndexOf(c)) return c;
  }
  return "_";
};
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, I follow up to there. In /*Test #2 var word = "abacabad"; */ since the first and last elements are not the same, should it not print out "d"? apologies for not being more clear, that's the part confusing me. How does the looping consider "a" and "d" to be the same?
@RobertPerez indexOf searches from the start of the array, and lastIndexOf searches from the end of the array.
It's not comparing "a" and "d". It's comparing the first and last index of arr[i]. arr[i] will be "a" first then "b" then "a" then "c" etc.
@RockySims THAT'S what i was missing. I misunderstood how the index was being used. Thanks!
0

Your function defined here returns the first non-repeating character in the given string.

The split function is here outputs the string as an array. The indexOf returns the first index of the character in the array while lastIndexOf returns the last index of the character in an array. So, if both the indexes are equal, the character occurs only once.

You can also do this using the spread operator as below

var word = "abcdefghijklmnopqrstuvwxyziflskecznslkjfabe";
firstNotRepeatingChar = arr => {
  for (var i = 0; i < arr.length; i++) {
    if (arr.indexOf(arr[i]) == arr.lastIndexOf(arr[i]))
      return arr[i];
  }
  return "_";
};

console.log(firstNotRepeatingChar([...word]));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.