Maximum distance between two occurrences of same element in array | Function to find maximum distance between equal elements ; Used to store element to first index mapping ; Traverse elements and find maximum distance between same occurrences with the help of map . ; If this is first occurrence of element , insert its index in map ; Else update max distance ; Driver program
function maxDistance ( arr , n ) { let map = new Map ( ) ; let max_dist = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( ! map . has ( arr [ i ] ) ) map . set ( arr [ i ] , i ) ; else max_dist = Math . max ( max_dist , i - map . get ( arr [ i ] ) ) ; } return max_dist ; } let arr = [ 3 , 2 , 1 , 2 , 1 , 4 , 5 , 8 , 6 , 7 , 4 , 2 ] ; let n = arr . length ; document . write ( maxDistance ( arr , n ) ) ;