For those who didn't understand why exactly(K) = atMost(K) - atMost(K-1) works....
Well, suppose you have a room with a bunch of children in it. It turns out that there are 12 children who are five years old or under, and 8 children who are fo
Well, suppose you have a room with a bunch of children in it. It turns out that there are 12 children who are five years old or under, and 8 children who are four years old or under.\n\nNow presumably you agree that each one of the "children four years old or under" is also one of the "children five years old or under," right?\n\nSo suppose we take the 12 children five years old or younger, and remove from them the 8 children four years old or younger. Of course, 12 - 8 = 4 children remain.\n\nNow, how old is each of these children?\n\nBelow I am sharing the solution using variable sized sliding window based on above approach.\n```\nclass Solution {\n  public int subarraysWithKDistinct(int[] nums, int k) {\n\n    return subarraysWithKSize(nums, k) - subarraysWithKSize(nums, k - 1);\n  }\n    \n    //Function for at-most k distinct\n    \n  public int subarraysWithKSize(int[] nums, int k) {\n    HashMap < Integer, Integer > hs = new HashMap < > ();\n    int count = 0;\n    int i = 0;\n    int j = 0;\n    while (j < nums.length) {\n      hs.put(nums[j], hs.getOrDefault(nums[j], 0) + 1);\n\n      while (hs.size() == k + 1) \n      { \n        hs.put(nums[i], hs.get(nums[i]) - 1);\n        if (hs.get(nums[i]) == 0)\n          hs.remove(nums[i]);\n        i++;\n\n      }\n\n      count += j - i + 1;\n      j++;\n\n    }\n\n    return count;\n\n  }\n}\n```
['Sliding Window', 'Java']