Python Easy Solution
\n\n# Code\n\nfrom collections import defaultdict\nclass Solution:\n    def atmostk(self,n,k,nums):\n        l=0\n        r=0\n        map=defaultdict(int)\n   
\n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n    def atmostk(self,n,k,nums):\n        l=0\n        r=0\n        map=defaultdict(int)\n        ans=0\n        while r<n:\n            map[nums[r]]+=1\n            while len(map)>k:\n                map[nums[l]]-=1\n                if map[nums[l]]==0:\n                    del map[nums[l]]\n                l+=1\n            \n            ans+=r-l+1\n            r+=1\n        return ans\n    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n        return self.atmostk(len(nums),k,nums)-self.atmostk(len(nums),k-1,nums)\n```
['Sliding Window', 'Python3']