File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ # Python 3 program to find minimum range
2+ # that contains exactly k distinct numbers.
3+
4+ # Prints the minimum range that contains
5+ # exactly k distinct numbers.
6+ def minRange (arr , n , k ):
7+
8+ l = 0
9+ r = n
10+
11+ # Consider every element as
12+ # starting point.
13+ for i in range (n ):
14+
15+ # Find the smallest window starting
16+ # with arr[i] and containing exactly
17+ # k distinct elements.
18+ s = []
19+ for j in range (i , n ) :
20+ s .append (arr [j ])
21+ if (len (s ) == k ):
22+ if ((j - i ) < (r - l )) :
23+ r = j
24+ l = i
25+
26+ break
27+
28+ # There are less than k distinct
29+ # elements now, so no need to continue.
30+ if (j == n ):
31+ break
32+
33+ # If there was no window with k distinct
34+ # elements (k is greater than total
35+ # distinct elements)
36+ if (l == 0 and r == n ):
37+ print ("Invalid k" )
38+ else :
39+ print (l , r )
40+
41+ # Driver code
42+ if __name__ == "__main__" :
43+
44+ arr = [ 1 , 2 , 3 , 4 , 5 ]
45+ n = len (arr )
46+ k = 3
47+ minRange (arr , n , k )
48+
49+
You can’t perform that action at this time.
0 commit comments