Find and return the first instance of a non-repeating character in a string s

Find and return the first instance of a non-repeating character in a string s
0

#1

Could anyone here help me by show what is error in this code?

function firstNotRepeatingCharacter(s) {
           for (let i = 0; i < s.length; i++) {
                   let repeat = 0;
                   for (let j = 0; i < s.length; j++) {
                      if( i!= j && s[i] == s[j]){
                        repeat =1;
                        break ;
                      }
                   }
                   if (repeat == 0) {
                     return s[i];
                  }
                }
             return '';
       }

Could anyone here help me by showing what error is in this code below?


#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

I see a few possible problems, but it’s hard to tell which one is causing your current error without you telling us what it is.


#4

I tested your code with the string ‘aadb’ which I assume based on your topic title should return ‘d’. This call creates an infinite loop. So you can see what the values of various variables are in your code, I added console.log statements (see below).

function firstNotRepeatingCharacter(s) {
  for (let i = 0; i < s.length; i++) {
    let repeat = 0;
    console.log('i='+i);
    for (let j = 0; i < s.length; j++) {
      console.log('j='+j);
      console.log('s[i]=' + s[i] + '  s[j]=' + s[j]);
      console.log('i != j is ' + (i != j) + ', s[i] == s[j] is ' + (s[i] == s[j]));
      if (i != j && s[i] == s[j]) {
        repeat = 1;
        break;
      }
    }
    if (repeat == 0) {
      return s[i];
    }
    console.log('repeat = ' + repeat + '\n');
  }
  return '';
}

firstNotRepeatingCharacter('aadb');

As you can see below, when the code above runs, once i = 2, j keeps getting larger and your repeat never gets set to 0, which is your exit condition. I only posted up to i=2 and j=5, because it just keeps repeating the same after that.

i=0
j=0
s[i]=a s[j]=a
i != j is false, s[i] == s[j] is true
j=1
s[i]=a s[j]=a
i != j is true, s[i] == s[j] is true
repeat = 1

i=1
j=0
s[i]=a s[j]=a
i != j is true, s[i] == s[j] is true
repeat = 1

i=2
j=0
s[i]=d s[j]=a
i != j is true, s[i] == s[j] is false
j=1
s[i]=d s[j]=a
i != j is true, s[i] == s[j] is false
j=2
s[i]=d s[j]=d
i != j is false, s[i] == s[j] is true
j=3
s[i]=d s[j]=b
i != j is true, s[i] == s[j] is false
j=4
s[i]=d s[j]=undefined
i != j is true, s[i] == s[j] is false
j=5
s[i]=d s[j]=undefined
i != j is true, s[i] == s[j] is false