Minimum distance between any most frequent and least frequent element of an array | Java implementation of the approach ; Function to find the minimum distance between any two most and least frequent element ; Initialize sets to store the least and the most frequent elements ; Initialize variables to store max and min frequency ; Initialize HashMap to store frequency of each element ; Loop through the array ; Store the count of each element ; Store the least and most frequent elements in the respective sets ; Store count of current element ; If count is equal to max count ; Store in max set ; If count is greater then max count ; Empty max set ; Update max count ; Store in max set ; If count is equal to min count ; Store in min set ; If count is less then max count ; Empty min set ; Update min count ; Store in min set ; Initialize a variable to store the minimum distance ; Initialize a variable to store the last index of least frequent element ; Traverse array ; If least frequent element ; Update last index of least frequent element ; If most frequent element ; Update minimum distance ; Traverse array from the end ; If least frequent element ; Update last index of least frequent element ; If most frequent element ; Update minimum distance ; Print the minimum distance ; Driver Code ; Given array ; Function Call
import java . util . * ; class GFG { public static void getMinimumDistance ( int a [ ] , int n ) { Set < Integer > min_set = new HashSet < > ( ) ; Set < Integer > max_set = new HashSet < > ( ) ; int max = 0 , min = Integer . MAX_VALUE ; HashMap < Integer , Integer > frequency = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { frequency . put ( a [ i ] , frequency . getOrDefault ( a [ i ] , 0 ) + 1 ) ; } for ( int i = 0 ; i < n ; i ++ ) { int count = frequency . get ( a [ i ] ) ; if ( count == max ) { max_set . add ( a [ i ] ) ; } else if ( count > max ) { max_set . clear ( ) ; max = count ; max_set . add ( a [ i ] ) ; } if ( count == min ) { min_set . add ( a [ i ] ) ; } else if ( count < min ) { min_set . clear ( ) ; min = count ; min_set . add ( a [ i ] ) ; } } int min_dist = Integer . MAX_VALUE ; int last_min_found = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( min_set . contains ( a [ i ] ) ) last_min_found = i ; if ( max_set . contains ( a [ i ] ) && last_min_found != - 1 ) { min_dist = Math . min ( min_dist , i - last_min_found ) ; } } last_min_found = - 1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( min_set . contains ( a [ i ] ) ) last_min_found = i ; if ( max_set . contains ( a [ i ] ) && last_min_found != - 1 ) { min_dist = Math . min ( min_dist , last_min_found - i ) ; } } System . out . println ( min_dist ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 3 , 2 , 3 , 3 } ; int N = arr . length ; getMinimumDistance ( arr , N ) ; } }