Leetcode 1034 Solution

This article provides solution to leetcode question 1034 (subarrays-with-k-different-integers)

https://leetcode.com/problems/subarrays-with-k-different-integers

Solution

class Solution:
    def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
        m = collections.defaultdict(list)

        ans = 0
        l = 0
        r = 0
        last_pos = 0
        while r < len(A):
            while r < len(A) and (len(m) < K or (len(m) == K and A[r] in m)):
                m[A[r]].append(r)
                last_pos = max(m[A[r]][0], last_pos)
                r += 1

            while len(m) == K:
                ans += r - last_pos

                m[A[l]].pop(0)
                if len(m[A[l]]) == 0:
                    m.pop(A[l])
                else:
                    last_pos = max(last_pos, m[A[l]][0])
                l += 1

        return ans