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
using System ; using System . Collections . Generic ; public class GFG { public static void getMinimumDistance ( int [ ] a , int n ) { HashSet < int > min_set = new HashSet < int > ( ) ; HashSet < int > max_set = new HashSet < int > ( ) ; int max = 0 , min = Int32 . MaxValue ; Dictionary < int , int > frequency = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! frequency . ContainsKey ( a [ i ] ) ) frequency . Add ( a [ i ] , 0 ) ; frequency [ a [ i ] ] ++ ; } for ( int i = 0 ; i < n ; i ++ ) { int count = frequency [ 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 = Int32 . MaxValue ; 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 ) ; } } Console . WriteLine ( min_dist ) ; } static public void Main ( ) { int [ ] arr = { 1 , 1 , 2 , 3 , 2 , 3 , 3 } ; int N = arr . Length ; getMinimumDistance ( arr , N ) ; } }