Duplicates in an array in O ( n ) time and by using O ( 1 ) extra space | Set | C ++ program to print all elements that appear more than once . ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printDuplicates ( int arr [ ] , int n ) { int i ; int fl = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ arr [ i ] % n ] >= n ) { if ( arr [ arr [ i ] % n ] < 2 * n ) { cout << arr [ i ] % n << " ▁ " ; fl = 1 ; } } arr [ arr [ i ] % n ] += n ; } if ( ! fl ) cout << " - 1" ; } int main ( ) { int arr [ ] = { 1 , 6 , 3 , 1 , 3 , 6 , 6 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printDuplicates ( arr , arr_size ) ; return 0 ; }