Repeated Character Whose First Appearance is Leftmost | Python3 program to find first repeating character ; The function returns index of the first repeating character in a string . If all characters are repeating then returns - 1 ; Mark all characters as not visited ; Traverse from right and update res as soon as we see a visited character . ; Driver program to test above function
NO_OF_CHARS = 256 NEW_LINE def firstRepeating ( string ) : NEW_LINE INDENT visited = [ False ] * NO_OF_CHARS ; NEW_LINE for i in range ( NO_OF_CHARS ) : NEW_LINE INDENT visited [ i ] = False ; NEW_LINE DEDENT res = - 1 ; NEW_LINE for i in range ( len ( string ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( visited [ string . index ( string [ i ] ) ] == False ) : NEW_LINE INDENT visited [ string . index ( string [ i ] ) ] = True ; NEW_LINE DEDENT else : NEW_LINE INDENT res = i ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE index = firstRepeating ( string ) ; NEW_LINE if ( index == - 1 ) : NEW_LINE INDENT print ( " Either ▁ all ▁ characters ▁ are " , " distinct ▁ or ▁ string ▁ is ▁ empty " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " First ▁ Repeating ▁ character ▁ is : " , string [ index ] ) ; NEW_LINE DEDENT DEDENT