Minimum operations required to make all the elements distinct in an array | Java program to find Minimum number of changes to make array distinct ; Function that returns minimum number of changes ; Hash - table to store frequency ; Increase the frequency of elements ; Traverse in the map to sum up the ( occurrences - 1 ) of duplicate elements ; Driver Code
import java . util . * ; class geeks { public static int minimumOperations ( int [ ] a , int n ) { HashMap < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . get ( a [ i ] ) != null ) { int x = mp . get ( a [ i ] ) ; mp . put ( a [ i ] , ++ x ) ; } else mp . put ( a [ i ] , 1 ) ; } int count = 0 ; for ( HashMap . Entry < Integer , Integer > entry : mp . entrySet ( ) ) { if ( entry . getValue ( ) > 1 ) { count += ( entry . getValue ( ) - 1 ) ; } } return count ; } public static void main ( String [ ] args ) { int [ ] a = { 2 , 1 , 2 , 3 , 3 , 4 , 3 } ; int n = a . length ; System . out . println ( minimumOperations ( a , n ) ) ; } }