Minimum distance between any most frequent and least frequent element of an array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getMinimumDistance ( int a [ ] , int n ) { set < int > min_set ; set < int > max_set ; int max = 0 , min = INT_MAX ; map < int , int > frequency ; for ( int i = 0 ; i < n ; i ++ ) { frequency [ a [ i ] ] += 1 ; } for ( int i = 0 ; i < n ; i ++ ) { int count = frequency [ a [ i ] ] ; if ( count == max ) { max_set . insert ( a [ i ] ) ; } else if ( count > max ) { max_set . clear ( ) ; max = count ; max_set . insert ( a [ i ] ) ; } if ( count == min ) { min_set . insert ( a [ i ] ) ; } else if ( count < min ) { min_set . clear ( ) ; min = count ; min_set . insert ( a [ i ] ) ; } } int min_dist = INT_MAX ; int last_min_found = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( min_set . find ( a [ i ] ) != min_set . end ( ) ) last_min_found = i ; if ( max_set . find ( a [ i ] ) != max_set . end ( ) && last_min_found != -1 ) { if ( ( i - last_min_found ) < min_dist ) min_dist = i - last_min_found ; } } last_min_found = -1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( min_set . find ( a [ i ] ) != min_set . end ( ) ) last_min_found = i ; if ( max_set . find ( a [ i ] ) != max_set . end ( ) && last_min_found != -1 ) { if ( ( last_min_found - i ) > min_dist ) min_dist = last_min_found - i ; } } cout << ( min_dist ) ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 , 2 , 3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getMinimumDistance ( arr , N ) ; }