Smallest subarray with k distinct numbers | C ++ 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 for above function .
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minRange ( int arr [ ] , int n , int k ) { int l = 0 , r = n ; for ( int i = 0 ; i < n ; i ++ ) { unordered_set < int > s ; int j ; for ( j = i ; j < n ; j ++ ) { s . insert ( 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 ) cout << " Invalid ▁ k " ; else cout << l << " ▁ " << r ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; minRange ( arr , n , k ) ; return 0 ; }