sliding window
two pointers
]
Leetcode 0992 Subarrays with K Different Integers
Problem statement
https://leetcode.com/problems/subarrays-with-k-different-integers/
Solution
The idea is the following: for each ending point let us find the length of the longest window with exactly K
different integers and the length of the shortest window with exactly K
different integers.
We will use sliding window approach here:
- First, we define
beg
andend
pointers equal to0
.vals
is counter of values inside window anddiff
is number of different values in window. - On each step we move
end
pointer one point to the right and updatevals
anddiff
- On the next step we move
beg
pointer to the right until number of different integers inside window becomes<= K
(or<= K-1
in another pass). -
For the first pass
window(K + 1)
we continue to expand our window to the left while we haveK
or less different symbols inside. Because we stopped one step later, we assignout[end] = end - beg + 1
is the length of longest window ending withend
point.For the second pass
window(K)
we continue to expand our window to the left while we haveK-1
symbols or less, so here we stop just at the moment when we haveK
symbols first time, so we need to add1
later.Finally, when we calculate for each
end
how many windows we have, it is exactly difference between two previously calculated numbers. Imagine, that we have[1, 2, 1, 2, 3]
for example. Then forend = 3
we have the smallest window ends with this place is[1, 2]
and the longest is[1, 2, 1, 2]
, so we have in total3
windows, which can be evaluated as4 - 1 = 4 - 2 + 1
, where4
is length of the longest window,2
is length of the shortest window and+1
because betweena
andb
there isb - a + 1
numbers.
Complexity
Both time and space complexity is O(n)
.
Code
class Solution:
def subarraysWithKDistinct(self, A, K):
def window(K):
beg, end, vals, diff = 0, 0, Counter(), 0
out = [None]*n
while end < n:
vals[A[end]] += 1
if vals[A[end]] == 1: diff += 1
while diff >= K:
if vals[A[beg]] == 1: diff -= 1
vals[A[beg]] -= 1
beg += 1
out[end] = end - beg + 1
end += 1
return sum(out)
n = len(A)
return window(K+1) - window(K)