Fill the missing numbers in the array of N natural numbers such that arr [ i ] not equal to i | C # implementation of above approach ; Function to fill the position with arr [ i ] = 0 ; Inserting all elements in missing [ ] set from 1 to N ; Inserting unfilled positions ; Removing allocated_elements ; Loop for filling the positions with arr [ i ] != i ; Checking for any arr [ i ] = i ; Finding the suitable position in the array to swap with found i for which arr [ i ] = i ; Checking if the position is present in unfilled_position ; Swapping arr [ i ] & arr [ pos ] ( arr [ pos ] = pos ) ; Function to Print the array ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static void solve ( int [ ] arr , int n ) { HashSet < int > unfilled_indices = new HashSet < int > ( ) ; HashSet < int > missing = new HashSet < int > ( ) ; for ( int i = 1 ; i < n ; i ++ ) { missing . Add ( i ) ; } for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) { unfilled_indices . Add ( i ) ; } else { missing . Remove ( arr [ i ] ) ; } } int [ ] mi = new int [ missing . Count ] ; int l = 0 ; foreach ( int x in missing ) { mi [ l ++ ] = x ; } int m = missing . Count ; foreach ( int it in unfilled_indices ) { arr [ it ] = mi [ m - 1 ] ; m -- ; } int pos = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == i ) { pos = i ; } } if ( pos != 0 ) { for ( int i = 1 ; i < n ; i ++ ) { if ( pos != i ) { if ( unfilled_indices . Contains ( i ) ) { int x = arr [ i ] ; arr [ i ] = pos ; arr [ pos ] = x ; break ; } } } } printArray ( arr , n ) ; } static void printArray ( int [ ] arr , int n ) { for ( int i = 1 ; i < n ; i ++ ) { Console . Write ( arr [ i ] + " ▁ " ) ; } } static public void Main ( ) { int [ ] arr = { 0 , 7 , 4 , 0 , 3 , 0 , 5 , 1 } ; int n = arr . Length ; solve ( arr , n ) ; } }