Minimum distance between any most frequent and least frequent element of an array | 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 ; Given array ; Function Call
function getMinimumDistance ( a , n ) { var min_set = new Set ( ) ; var max_set = new Set ( ) ; var max = 0 , min = 1000000000 ; var frequency = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( frequency . has ( a [ i ] ) ) frequency . set ( a [ i ] , frequency . get ( a [ i ] ) + 1 ) else frequency . set ( a [ i ] , 1 ) } for ( var i = 0 ; i < n ; i ++ ) { var count = frequency . get ( a [ i ] ) ; if ( count == max ) { max_set . add ( a [ i ] ) ; } else if ( count > max ) { max_set = new Set ( ) ; max = count ; max_set . add ( a [ i ] ) ; } if ( count == min ) { min_set . add ( a [ i ] ) ; } else if ( count < min ) { min_set = new Set ( ) ; min = count ; min_set . add ( a [ i ] ) ; } } var min_dist = 1000000000 ; var last_min_found = - 1 ; for ( var i = 0 ; i < n ; i ++ ) { if ( min_set . has ( a [ i ] ) ) last_min_found = i ; if ( max_set . has ( a [ i ] ) && last_min_found != - 1 ) { if ( ( i - last_min_found ) < min_dist ) min_dist = i - last_min_found ; } } last_min_found = - 1 ; for ( var i = n - 1 ; i >= 0 ; i -- ) { if ( min_set . has ( a [ i ] ) ) last_min_found = i ; if ( max_set . has ( a [ i ] ) && last_min_found != - 1 ) { if ( ( last_min_found - i ) > min_dist ) min_dist = last_min_found - i ; } } document . write ( min_dist ) ; } var arr = [ 1 , 1 , 2 , 3 , 2 , 3 , 3 ] ; var N = arr . length ; getMinimumDistance ( arr , N ) ;