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
def solve ( arr , n ) : NEW_LINE INDENT unfilled_indices = { } NEW_LINE missing = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT missing [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT unfilled_indices [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT del missing [ arr [ i ] ] NEW_LINE DEDENT DEDENT it2 = list ( missing . keys ( ) ) NEW_LINE m = len ( it2 ) NEW_LINE for it in unfilled_indices : NEW_LINE INDENT arr [ it ] = it2 [ m - 1 ] NEW_LINE m -= 1 NEW_LINE DEDENT pos = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == i ) : NEW_LINE INDENT pos = i NEW_LINE DEDENT DEDENT x = 0 NEW_LINE if ( pos != 0 ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( pos != i ) : NEW_LINE INDENT if i in unfilled_indices : NEW_LINE INDENT x = arr [ i ] NEW_LINE arr [ i ] = pos NEW_LINE arr [ pos ] = x NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT printArray ( arr , n ) NEW_LINE DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 7 , 4 , 0 , 3 , 0 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE solve ( arr , n ) NEW_LINE DEDENT