Given a string , find its first non | CPP program to find first non - repeating character ; 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
# include <iostream> NEW_LINE # include <climits> NEW_LINE using namespace std ; int firstNonRepeating ( string str ) { int fi [ 256 ] ; for ( int i = 0 ; i < 256 ; i ++ ) fi [ i ] = -1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( fi [ str [ i ] ] == -1 ) { fi [ str [ i ] ] = i ; } else { fi [ str [ i ] ] = -2 ; } } int res = INT_MAX ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( fi [ i ] >= 0 ) res = min ( res , fi [ i ] ) ; } if ( res == INT_MAX ) return -1 ; else return res ; } int main ( ) { string str ; str = " geeksforgeeks " ; int firstIndex = firstNonRepeating ( str ) ; if ( firstIndex == -1 ) cout << " Either ▁ all ▁ characters ▁ are ▁ repeating ▁ or ▁ string ▁ is ▁ empty " ; else cout << " First ▁ non - repeating ▁ character ▁ is ▁ " << str [ firstIndex ] ; return 0 ; }