Given a string , find its first non | this function return the index of first non - repeating character if found , or else it returns - 1 ; initializing all elements to - 1 ; sets all repeating characters to - 2 and non - repeating characters contain the index where they occur ; If this character is not - 1 or - 2 then it means that this character occurred only once so find the min index of all characters that occur only once , that 's our first index ; if res remains INT_MAX , it means there are no characters that repeat only once or the string is empty
function firstNonRepeating ( str ) { var fi = new Array ( 256 ) ; fi . fill ( - 1 ) ; for ( var i = 0 ; i < 256 ; i ++ ) fi [ i ] = - 1 ; for ( var i = 0 ; i < str . length ; i ++ ) { if ( fi [ str . charCodeAt ( i ) ] == - 1 ) { fi [ str . charCodeAt ( i ) ] = i ; } else { fi [ str . charCodeAt ( i ) ] = - 2 ; } } var res = Infinity ; for ( var i = 0 ; i < 256 ; i ++ ) { if ( fi [ i ] >= 0 ) res = Math . min ( res , fi [ i ] ) ; } if ( res == Infinity ) return - 1 ; else return res ; } var str ; str = " " ; var firstIndex = firstNonRepeating ( str ) ; if ( firstIndex === - 1 ) document . write ( " " ) ; else document . write ( " " + str . charAt ( firstIndex ) ) ;