Change the array into a permutation of numbers from 1 to n | JavaScript program to make a permutation of numbers from 1 to n using minimum changes . ; Store counts of all elements . ; Find next missing element to put in place of current element . ; Replace with next missing and insert the missing element in hash . ; Driver Code
function makePermutation ( a , n ) { var count = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( count . has ( a [ i ] ) ) count . set ( a [ i ] , count . get ( a [ i ] ) + 1 ) else count . set ( a [ i ] , 1 ) } var next_missing = 1 ; for ( var i = 0 ; i < n ; i ++ ) { if ( count . get ( a [ i ] ) != 1 a [ i ] > n a [ i ] < 1 ) { count . set ( a [ i ] , count . get ( a [ i ] ) - 1 ) ; while ( count . has ( next_missing ) ) next_missing ++ ; a [ i ] = next_missing ; count . set ( next_missing , 1 ) ; } } } var A = [ 2 , 2 , 3 , 3 ] ; var n = A . length ; makePermutation ( A , n ) ; for ( var i = 0 ; i < n ; i ++ ) document . write ( A [ i ] + " " ) ;