Smallest subarray with k distinct numbers | Java program to find minimum range that contains exactly k distinct numbers . ; Prints the minimum range that contains exactly k distinct numbers . ; Consider every element as starting point . ; Find the smallest window starting with arr [ i ] and containing exactly k distinct elements . ; There are less than k distinct elements now , so no need to continue . ; If there was no window with k distinct elements ( k is greater than total distinct elements ) ; Driver code
import java . util . * ; class GFG { static void minRange ( int arr [ ] , int n , int k ) { int l = 0 , r = n ; for ( int i = 0 ; i < n ; i ++ ) { Set < Integer > s = new HashSet < Integer > ( ) ; int j ; for ( j = i ; j < n ; j ++ ) { s . add ( arr [ j ] ) ; if ( s . size ( ) == k ) { if ( ( j - i ) < ( r - l ) ) { r = j ; l = i ; } break ; } } if ( j == n ) break ; } if ( l == 0 && r == n ) System . out . println ( " Invalid ▁ k " ) ; else System . out . println ( l + " ▁ " + r ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . length ; int k = 3 ; minRange ( arr , n , k ) ; } }