Find the first repeating element in an array of integers | 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
function printFirstRepeating ( arr , n ) { var k = 0 ; var max = n ; for ( i = 0 ; i < n ; i ++ ) if ( max < arr [ i ] ) max = arr [ i ] ; var a = Array ( max + 1 ) . fill ( 0 ) ; var b = Array ( max + 1 ) . fill ( 0 ) ; for ( var 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 ) document . write ( " " ) ; else { var min = max + 1 ; for ( i = 0 ; i < max + 1 ; i ++ ) if ( a [ i ] != 0 && min > a [ i ] && b [ i ] != 0 ) min = a [ i ] ; document . write ( arr [ min ] ) ; } document . write ( " " ) ; } var arr = [ 10 , 5 , 3 , 4 , 3 , 5 , 6 ] ; var n = arr . length ; printFirstRepeating ( arr , n ) ;