Skip to content

Commit 144c737

Browse files
Merge pull request codemistic#476 from Aman5989/patch-17
create Smallest-subarray-with-k-distinct-number.py
2 parents a63a243 + 3e56f71 commit 144c737

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+

0 commit comments

Comments
 (0)