Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.
(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)
Return the number of good subarrays of A.
 
Example 1:
Input: A = [1,2,1,2,3], K = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Example 2:
Input: A = [1,2,1,3,4], K = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

 
Note:

1 <= A.length <= 20000
1 <= A[i] <= A.length
1 <= K <= A.length

```python

USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
    import resource as _res
except Exception:
    _res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
    from typing import *
except Exception:
    pass
try:
    sys.setrecursionlimit(1_000_000)
except Exception:
    pass
try:
    import site as _site
    try:
        _sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
        for _p in _sys_sites:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
    try:
        _usp = _site.getusersitepackages()
        if isinstance(_usp, str):
            _usp = [_usp]
        for _p in _usp:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
except Exception:
    pass

def _disabled_input(*args, **kwargs):
    raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input

ns = {"__name__": "__judge__"}  # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
    if not _k.startswith("_"):
        ns[_k] = _v
_CODE = 'from collections import defaultdict\nclass Solution:\n    def subarraysWithKDistinct(self, A: List[int], K: int) -> int:\n        n = len(A)\n        if n < K:\n            return 0\n        \n        # 3 pointer sliding window\n        # p1 points to the 1st unique integer, start of the window\n        # p2 points to the first occurrance of the Kth unique integer after p1\n        # p3 points the the first occurrance of the next unique integer after p2, of end of string at n\n        # Given such a window, we add (p3-p2) to the count\n        # Then move p1 by 1. Check if that reduces the number of integers to K-1. If no, add p3-p2 again.\n        # If yes, then move p2 until the count goes up to K again. If p2 lands on p3 when doing this,\n        # then need to move p3 to the next integer. If p3 is already at EOS, return\n        \n        # To maintain the number of unique integers in a window, we\'ll use a hashmap\n        # Be careful, we need this dict to contain only nonzero count entries. So if a count becomes zero, delete it!\n        count = defaultdict(int)\n        p1 = 0; p2 = 0; p3 = 0\n        count[A[0]] += 1\n        ans = 0\n        while p2 < n:  # IMP!!! note the <=, not < \n            # Move p2 until the number of unique integers in the window hits K\n            remaining = K-len(count)\n            while remaining > 0:\n                p2 += 1\n                if p2 == n:\n                    return ans\n                count[A[p2]] += 1\n                if count[A[p2]] == 1:\n                    remaining -= 1\n            # p2 now points to the first instance of the Kth integer after p1\n            # Now move p3 to the next unique integer after p2\n            # print(\\"count: {}, A[{}]: {}, {}\\".format(count, p3, A[p3], A[p3] in count))\n            while p3 < n and A[p3] in count:\n                p3 += 1\n            # p3 is either n or points to the (K+1)th integer after p1\n            # Now, keep adding (p3-p2) to the count and advancing p1 until we no longer have K integers in this window\n            while len(count) == K:\n                ans += (p3-p2)\n                # print(\\"p1:{}, p2:{}, p3:{}, count:{}\\".format(p1, p2, p3, count))\n                p1 += 1\n                count[A[p1-1]] -= 1\n                if count[A[p1-1]] == 0:\n                    del count[A[p1-1]]\n        return ans'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)

_target = None
_fn_name = 'subarraysWithKDistinct'
if _fn_name:
    if "Solution" in ns:
        try:
            _obj = ns["Solution"]()
            if hasattr(_obj, _fn_name):
                _target = getattr(_obj, _fn_name)
        except Exception:
            _target = None
    if _target is None and _fn_name in ns and callable(ns[_fn_name]):
        _target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
    _cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
    _user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
    if len(_user_funcs) == 1:
        _target = _user_funcs[0]
if _target is None:
    raise RuntimeError(f"Could not resolve callable '{_fn_name}'")

_raw = sys.stdin.read().strip()
if _raw:
    _parsed = json.loads(_raw)
    if isinstance(_parsed, dict):
        _kwargs = _parsed.get("kwargs", {})
        _args = _parsed.get("args", [])
    else:
        _args, _kwargs = _parsed, {}
else:
    _args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
    _args = [_args]
_res = _target(*_args, **_kwargs)
try:
    sys.stdout.write(repr(_res) + "\n")
except Exception:
    pass

```

Measured memory_bytes: 5904