Find the first repeating element in an array of integers | Java program to find first repeating element in arr [ ] ; This function prints the first repeating element in arr [ ] ; This will set k = 1 , if any repeating element found ; max = maximum from ( all elements & n ) ; Array a is for storing 1 st time occurence of element initialized by 0 ; Store 1 in array b if element is duplicate initialized by 0 ; Duplicate element found ; storing 1 st occurence of arr [ i ] ; trace array a & find repeating element with min index ; Driver code
public class GFG { static void printFirstRepeating ( int [ ] arr , int n ) { int k = 0 ; int max = n ; for ( int i = 0 ; i < n ; i ++ ) if ( max < arr [ i ] ) max = arr [ i ] ; int [ ] a = new int [ max + 1 ] ; int [ ] b = new int [ max + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ arr [ i ] ] != 0 ) { b [ arr [ i ] ] = 1 ; k = 1 ; continue ; } else a [ arr [ i ] ] = i ; } if ( k == 0 ) System . out . println ( " No ▁ repeating ▁ element ▁ found " ) ; else { int min = max + 1 ; for ( int i = 0 ; i < max + 1 ; i ++ ) if ( a [ i ] != 0 && min > a [ i ] && b [ i ] != 0 ) min = a [ i ] ; System . out . print ( arr [ min ] ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 10 , 5 , 3 , 4 , 3 , 5 , 6 } ; int n = arr . length ; printFirstRepeating ( arr , n ) ; } }