Easy Java solution using Sliding Window
class Solution {\n    \n    private int countAtmost(int nums[], int k)\n    {\n        int count=0;\n        HashMap map=new HashMap<>();\n        int i=0, j=0;
class Solution {\n    \n    private int countAtmost(int nums[], int k)\n    {\n        int count=0;\n        HashMap<Integer, Integer> map=new HashMap<>();\n        int i=0, j=0;\n        while(j<nums.length)\n        {\n            map.put(nums[j], map.getOrDefault(nums[j], 0)+1);\n            while(map.size()>k)\n            {\n                map.put(nums[i], map.getOrDefault(nums[i], 0)-1);\n                if(map.get(nums[i])==0)\n                    map.remove(nums[i]);\n                i++;\n            }\n            count+=j-i+1;\n            j++;\n        }\n        return count;\n    }\n    \n    public int subarraysWithKDistinct(int[] nums, int k) {\n        return countAtmost(nums, k) - countAtmost(nums, k-1);\n    }\n}
['Array', 'Sliding Window', 'Java']