Smallest subarray having an element with frequency greater than that of other elements | Java program for the above approach ; 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
import java . util . * ; class GFG { public static void FindSubarray ( int [ ] arr , int n ) { if ( n == 1 ) { System . out . println ( " No ▁ such ▁ subarray ! " ) ; } int [ ] vis = new int [ n + 1 ] ; Arrays . fill ( vis , - 1 ) ; vis [ arr [ 0 ] ] = 0 ; int len = Integer . MAX_VALUE , flag = 0 ; int start = 0 , end = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int t = arr [ i ] ; if ( vis [ t ] != - 1 ) { int distance = i - vis [ t ] + 1 ; if ( distance < len ) { len = distance ; start = vis [ t ] ; end = i ; } flag = 1 ; } vis [ t ] = i ; } if ( flag == 0 ) System . out . println ( " No ▁ such ▁ subarray ! " ) ; else { for ( int i = start ; i <= end ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 2 , 4 , 5 } ; int n = arr . length ; FindSubarray ( arr , n ) ; } }