Duplicates in an array in O ( n ) time and by using O ( 1 ) extra space | Set | Function to find repeating elements ; Flag variable used to represent whether repeating element is found or not . ; Check if current element is repeating or not . If it is repeating then value will be greater than or equal to n . ; Check if it is first repetition or not . If it is first repetition then value at index arr [ i ] is less than 2 * n . Print arr [ i ] if it is first repetition . ; Add n to index arr [ i ] to mark presence of arr [ i ] or to mark repetition of arr [ i ] . ; If flag variable is not set then no repeating element is found . So print - 1. ; Driver Function
< ? php function printDuplicates ( $ arr , $ n ) { $ i ; $ fl = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ arr [ $ i ] % $ n ] >= $ n ) { if ( $ arr [ $ arr [ $ i ] % $ n ] < 2 * $ n ) { echo $ arr [ $ i ] % $ n . " " ; $ fl = 1 ; } } $ arr [ $ arr [ $ i ] % $ n ] += $ n ; } if ( ! $ fl ) echo " - 1" ; } $ arr = array ( 1 , 6 , 3 , 1 , 3 , 6 , 6 ) ; $ arr_size = sizeof ( $ arr ) ; printDuplicates ( $ arr , $ arr_size ) ;