Change the array into a permutation of numbers from 1 to n | C # 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
using System ; using System . Collections . Generic ; class GFG { static void makePermutation ( int [ ] a , int n ) { Dictionary < int , int > count = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( count . ContainsKey ( a [ i ] ) ) { count [ a [ i ] ] = count [ a [ i ] ] + 1 ; } else { count . Add ( a [ i ] , 1 ) ; } } int next_missing = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( count . ContainsKey ( a [ i ] ) && count [ a [ i ] ] != 1 a [ i ] > n a [ i ] < 1 ) { count [ a [ i ] ] = count [ a [ i ] ] - 1 ; while ( count . ContainsKey ( next_missing ) ) next_missing ++ ; a [ i ] = next_missing ; count . Add ( next_missing , 1 ) ; } } } public static void Main ( String [ ] args ) { int [ ] A = { 2 , 2 , 3 , 3 } ; int n = A . Length ; makePermutation ( A , n ) ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( A [ i ] + " ▁ " ) ; } }