Smallest subarray with 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
function minRange ( arr , n , k ) { let l = 0 , r = n ; for ( let i = 0 ; i < n ; i ++ ) { let s = new Set ( ) ; let 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 ) document . write ( " " ) ; else document . write ( l + " " + r ) ; } let arr = [ 1 , 2 , 3 , 4 , 5 ] ; let n = arr . length ; let k = 3 ; minRange ( arr , n , k ) ;