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
def minRange ( arr , n , k ) : NEW_LINE INDENT l = 0 NEW_LINE r = n NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = [ ] NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT s . append ( arr [ j ] ) NEW_LINE if ( len ( s ) == k ) : NEW_LINE INDENT if ( ( j - i ) < ( r - l ) ) : NEW_LINE INDENT r = j NEW_LINE l = i NEW_LINE DEDENT break NEW_LINE DEDENT DEDENT if ( j == n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( l == 0 and r == n ) : NEW_LINE INDENT print ( " Invalid ▁ k " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( l , r ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE minRange ( arr , n , k ) NEW_LINE DEDENT