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
using System ; using System . Collections . Generic ; public class GFG { public static void minRange ( int [ ] arr , int n , int k ) { int l = 0 , r = n ; for ( int i = 0 ; i < n ; i ++ ) { ISet < int > s = new HashSet < int > ( ) ; int j ; for ( j = i ; j < n ; j ++ ) { s . Add ( arr [ j ] ) ; if ( s . Count == k ) { if ( ( j - i ) < ( r - l ) ) { r = j ; l = i ; } break ; } } if ( j == n ) { break ; } } if ( l == 0 && r == n ) { Console . WriteLine ( " Invalid ▁ k " ) ; } else { Console . WriteLine ( l + " ▁ " + r ) ; } } public static void Main ( string [ ] args ) { int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 , 5 } ; int n = arr . Length ; int k = 3 ; minRange ( arr , n , k ) ; } }