First non | C # program to find first non - repeating character using 1D array and one traversal . ; The function returns index of the first non - repeating character in a string . If all characters are repeating then returns INT_MAX ; Initialize all characters as absent . ; After below loop , the value of arr [ x ] is going to be index of x if x appears only once . Else the value is going to be either - 1 or - 2. ; If this character occurs only once and appears before the current result , then update the result ; Driver Code
using System ; class GFG { static int firstNonRepeating ( String str ) { int NO_OF_CHARS = 256 ; int [ ] arr = new int [ NO_OF_CHARS ] ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) arr [ i ] = - 1 ; for ( int i = 0 ; i < str . Length ; i ++ ) { if ( arr [ str [ i ] ] == - 1 ) arr [ str [ i ] ] = i ; else arr [ str [ i ] ] = - 2 ; } int res = int . MaxValue ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( arr [ i ] >= 0 ) res = Math . Min ( res , arr [ i ] ) ; return res ; } public static void Main ( ) { String str = " geeksforgeeks " ; int index = firstNonRepeating ( str ) ; if ( index == int . MaxValue ) Console . Write ( " Either ▁ all ▁ characters ▁ are ▁ " + " repeating ▁ or ▁ string ▁ is ▁ empty " ) ; else Console . Write ( " First ▁ non - repeating ▁ character " + " ▁ is ▁ " + str [ index ] ) ; } }