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
begandendpointers equal to0.valsis counter of values inside window anddiffis number of different values in window. - On each step we move
endpointer one point to the right and updatevalsanddiff - On the next step we move
begpointer to the right until number of different integers inside window becomes<= K(or<= K-1in another pass). -
For the first pass
window(K + 1)we continue to expand our window to the left while we haveKor less different symbols inside. Because we stopped one step later, we assignout[end] = end - beg + 1is the length of longest window ending withendpoint.For the second pass
window(K)we continue to expand our window to the left while we haveK-1symbols or less, so here we stop just at the moment when we haveKsymbols first time, so we need to add1later.Finally, when we calculate for each
endhow 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 = 3we have the smallest window ends with this place is[1, 2]and the longest is[1, 2, 1, 2], so we have in total3windows, which can be evaluated as4 - 1 = 4 - 2 + 1, where4is length of the longest window,2is length of the shortest window and+1because betweenaandbthere isb - a + 1numbers.
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)