Find all duplicate and missing numbers in given permutation array of 1 to N | C ++ program for the above approach ; Function to find the duplicate and the missing elements over the range [ 1 , N ] ; Stores the missing and duplicate numbers in the array arr [ ] ; Making an iterator for set ; Traverse the given array arr [ ] ; Check if the current element is not same as the element at index arr [ i ] - 1 , then swap ; Otherwise , increment the index ; Traverse the array again ; If the element is not at its correct position ; Stores the missing and the duplicate elements ; Print the Missing Number ; Print the Duplicate Number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findElements ( int arr [ ] , int N ) { int i = 0 ; vector < int > missing ; set < int > duplicate ; set < int > :: iterator it ; while ( i != N ) { cout << i << " ▁ # ▁ " ; if ( arr [ i ] != arr [ arr [ i ] - 1 ] ) { swap ( arr [ i ] , arr [ arr [ i ] - 1 ] ) ; } else { i ++ ; } } for ( i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != i + 1 ) { missing . push_back ( i + 1 ) ; duplicate . insert ( arr [ i ] ) ; } } cout << " Missing ▁ Numbers : ▁ " ; for ( auto & it : missing ) cout << it << ' ▁ ' ; cout << " Duplicate Numbers : " for ( auto & it : duplicate ) cout << it << ' ▁ ' ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 2 , 4 , 5 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findElements ( arr , N ) ; return 0 ; }