Fill the missing numbers in the array of N natural numbers such that arr [ i ] not equal to i | 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
function solve ( arr , n ) { let unfilled_indices = new Set ( ) ; let missing = new Set ( ) ; for ( let i = 1 ; i < n ; i ++ ) { missing . add ( i ) ; } for ( let i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) { unfilled_indices . add ( i ) ; } else { missing . delete ( arr [ i ] ) ; } } let mi = new Array ( missing . size ) ; let l = 0 ; for ( let x of missing . values ( ) ) { mi [ l ++ ] = x ; } let m = missing . size ; for ( let it of unfilled_indices . values ( ) ) { arr [ it ] = mi [ m - 1 ] ; m -- ; } let pos = 0 ; for ( let i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == i ) { pos = i ; } } let x ; if ( pos != 0 ) { for ( let i = 1 ; i < n ; i ++ ) { if ( pos != i ) { if ( unfilled_indices . has ( i ) ) { x = arr [ i ] ; arr [ i ] = pos ; arr [ pos ] = x ; break ; } } } } printArray ( arr , n ) ; } function printArray ( arr , n ) { for ( let i = 1 ; i < n ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } let arr = [ 0 , 7 , 4 , 0 , 3 , 0 , 5 , 1 ] ; let n = arr . length ; solve ( arr , n ) ;