Repeated Character Whose First Appearance is Leftmost | Java 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 code
import java . util . * ; class GFG { static int NO_OF_CHARS = 256 ; static int firstRepeating ( String str ) { boolean [ ] visited = new boolean [ NO_OF_CHARS ] ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) visited [ i ] = false ; int res = - 1 ; for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { if ( visited [ str . charAt ( i ) ] == false ) visited [ str . charAt ( i ) ] = true ; else res = i ; } return res ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int index = firstRepeating ( str ) ; if ( index == - 1 ) System . out . printf ( " Either ▁ all ▁ characters ▁ are ▁ " + " distinct ▁ or ▁ string ▁ is ▁ empty " ) ; else System . out . printf ( " First ▁ Repeating ▁ character " + " ▁ is ▁ % c " , str . charAt ( index ) ) ; } }