Smallest subarray having an element with frequency greater than that of other elements | Function to find subarray ; If the array has only one element , then there is no answer . ; Array to store the last occurrences of the elements of the array . ; To maintain the length ; Variables to store start and end indices ; Check if element is occurring for the second time in the array ; Find distance between last and current index of the element . ; If the current distance is less then len update len and set ' start ' and ' end ' ; Set the last occurrence of current element to be ' i ' . ; If flag is equal to 0 , it means there is no answer . ; Driver code
function FindSubarray ( arr , n ) { if ( n == 1 ) { document . write ( " " ) ; } let vis = new Array ( n + 1 ) ; for ( let i = 0 ; i < ( n + 1 ) ; i ++ ) vis [ i ] = - 1 ; vis [ arr [ 0 ] ] = 0 ; let len = Number . MAX_VALUE , flag = 0 ; let start = 0 , end = 0 ; for ( let i = 1 ; i < n ; i ++ ) { let t = arr [ i ] ; if ( vis [ t ] != - 1 ) { let distance = i - vis [ t ] + 1 ; if ( distance < len ) { len = distance ; start = vis [ t ] ; end = i ; } flag = 1 ; } vis [ t ] = i ; } if ( flag == 0 ) document . write ( " " ) ; else { for ( let i = start ; i <= end ; i ++ ) document . write ( arr [ i ] + " " ) ; } } let arr = [ 2 , 3 , 2 , 4 , 5 ] ; let n = arr . length ; FindSubarray ( arr , n ) ;