Skip to content

Commit 1513148

Browse files
committed
Resolved 'Subarrays with K Different Integers' LeetCode problem with an optimized solution
1 parent 7527ca1 commit 1513148

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Subarrays with K Different Integers
2+
3+
class Solution:
4+
def subarraysWithKDistinct(self, nums, k):
5+
return self.subarraysWithAtMostKDistinct(nums, k) - self.subarraysWithAtMostKDistinct(nums, k - 1)
6+
7+
def subarraysWithAtMostKDistinct(self, nums, k):
8+
ans = 0
9+
count = [0] * (len(nums) + 1)
10+
11+
l = 0
12+
for r in range(len(nums)):
13+
count[nums[r]] += 1
14+
if count[nums[r]] == 1:
15+
k -= 1
16+
while k == -1:
17+
count[nums[l]] -= 1
18+
if count[nums[l]] == 0:
19+
k += 1
20+
l += 1
21+
ans += r - l + 1
22+
return ans
23+
24+
solution = Solution()
25+
print(solution.subarraysWithAtMostKDistinct([1,2,1,2,3], 2))

0 commit comments

Comments
 (0)