Robster
Robster

Reputation: 222

Please help understanding function

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!

Upvotes: -1

Views: 64

Answers (2)

Rocky Sims
Rocky Sims

Reputation: 3598

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 "_";
};

Upvotes: 4

Nidhin Joseph
Nidhin Joseph

Reputation: 10227

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]));

Upvotes: 0

Related Questions